each loop in underscore.js template

Joel picture Joel · Sep 9, 2011 · Viewed 43.6k times · Source

I'm doing something wrong here but I can't see it! Im trying to loop an array in a underscore template. It doesn't work though so I'm missing something, Here's my code, my templates work fine otherwise, it's just the _.each stuff that's bugging out:

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

I've also done some template settings like this:

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

Answer

mjtognetti picture mjtognetti · Sep 15, 2011

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