TemplateSettings not working

I get a compilation error at runtime when I try to make the following pattern:

<script id="tmpl-books" type="text/template"> <% _.each(items, function(item) { %> <ul> <li>Title: <%= item.title %></li> <li>Author: <%= item.author %></li> </ul> <% }); %> </script> 

 <script type="text/javascript"> _.templateSettings = { evaluate: /\{\{=(.+?)\}\}/g, interpolate: /\{\{(.+?)\}\}/g, escape: /\{\{-(.+?)\}\}/g }; var list = { items: [ { "title": "Myst: The Book of Atrus", "author": "Rand Miller" }, { "title": "The Hobbit", "author": "JRR Tolkien" }, { "title": "Stardust", "author": "Neil Gaiman" }] }; $(document).ready(function () { var tmplMarkup = $('#tmpl-books').html(); // ...tell Underscore to render the template... var compiledTmpl = _.template(tmplMarkup, list); // ...and update part of your page: $('#rendered').append(compiledTmpl); }); </script> 
+4
source share
1 answer

You have two problems:

  • Your regular expressions templateSettings do not match.
  • Your templateSettings does not match your template.

The documentation is not explicit about the order in which regular expressions are applied, but the source code

 var matcher = new RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); 

In particular, interpolate will be matched before evaluate . Your interpolate looking for things like {{ ... }} , so it will select things like {{= ... }} so that your regular expression evaluate can see them. The result will be spurious = in the generated source code. Therefore, the interpolate regex cannot match what your evaluate looking for. You probably want to use these regular expressions:

 _.templateSettings = { evaluate: /\{\{(.+?)\}\}/g, interpolate: /\{\{=(.+?)\}\}/g, escape: /\{\{-(.+?)\}\}/g }; 

Please note that I switched those who are looking for {{= ... }} and {{ ... }} .

Then your template should use mustache-style delimiters, not the default:

 <script id="tmpl-books" type="text/template"> {{ _.each(items, function(item) { }} <ul> <li>Title: {{= item.title }}</li> <li>Author: {{= item.author }}</li> </ul> {{ }); }} </script> 

Fixing these two issues should make everything work.

Demo: http://jsfiddle.net/ambiguous/my49N/

+14
source

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


All Articles