each loop in underscore.js template

懵懂的女人 提交于 2019-12-02 18:59:33

Because you've only defined an interpolation regex in your custom template settings, underscore doesn't know when to evaluate expressions. When you define custom template settings you need to define and differentiate between interpolation and evaluation. From the underscore template() documentation:

Define an interpolate regex, and an (optional) evaluate regex to match expressions that should be inserted and evaluated, respectively. If no evaluate regex is provided, your templates will only be capable of interpolating values.

In a standard (no custom settings) template the difference is evaluation: <% %> and value interpolation: <%= %>.

So, for example, your template above should be (with standard template settings):

<% _.each([0,1,2,3,4], function(i) { %>  <p><%= i %></p> <% }); %>

If you want to continue using custom settings you'll need to define an evaluation regex in _.templateSettings as well. Based on your questions and comments something like:

   _.templateSettings = {
      interpolate: /\<\@\=(.+?)\@\>/gim,
      evaluate: /\<\@(.+?)\@\>/gim
  };

And then update your template to use the evaluation form around code blocks and the interpolation form around values, like so:

<script type="text/template" id="pageContent">
    <div class="col2">
        <@ _.each([0,1,2,3,4], function(i) { @>  <p><@= i @></p> <@ }); @>
    </div>    
</script>

source: http://documentcloud.github.com/underscore/#template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!