Jquery and html5 tags

I want to use the underscorejs template function. It seems that the HTML5 <template> would be suitable for this, but there was a catch ... Underscorejs interpolation tags ( <% and %> get html-escaped, so the HTML inside the template tag looks like this:

 $('template.new-email').html() 

=>

 " <div class="email"> <div class="timestamp"> &lt;%= received %&gt; </div> <div class="from"> &lt;%= from %&gt; </div> <div class="title"> &lt;%= title %&gt; </div> <div class="message"> &lt;%= message %&gt; </div> </div> " 

Well, that sucks.

Now, as it turned out, if I use a script tag with a dummy type, for example, "x-underscore-templates", then it looks hunky-dory:

 $('.new-email').html() 

=>

 " <div class="email"> <div class="timestamp"> <%= received %> </div> <div class="from"> <%= from %> </div> <div class="title"> <%= title %> </div> <div class="message"> <%= message %> </div> </div> " 

So my question is: can I use a template tag? How to get only the characters I need in a string so that I can pass them to emphasize the template system?

Note. Since the server I'm using now is a hapijs / node server that uses descriptors as the server template system, I can't just use {{and}}.

+5
source share
1 answer

I also like the idea of ​​using a template tag, and I tried to make underline patterns in the html5 template element in various ways. Unfortunately, the element specifically means the html template, and the content will be converted to a document fragment that is not suitable for many valid underline templates, even if they subsequently display valid html.

Therefore, the only use I can offer is that you could save the script elements organized inside the template element as follows:

 <template class="underscore-templates"> <script id="new-email"> <div class="email"> <div class="timestamp"> <%= received %> </div> <div class="from"> <%= from %> </div> <div class="title"> <%= title %> </div> <div class="message"> <%= message %> </div> </div> </script> <script id="other"> </script> </template> 

And then they are separated to safely do things like:

 var templates = $('.underscore-templates').prop('content'); _.template($(templates).children('#new-email').html(), {...}); 

with a template element that serves as a scope to prevent common problems with an identifier conflict and to execute these templates as scripts.

(However, this will be limited to modern browsers without a thorough study of how (or maybe if) you can get the contents of the template elements in older browsers and make it searchable by snippet.)

+6
source

Source: https://habr.com/ru/post/1207829/


All Articles