Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

each loop in underscore.js template

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 }; 
like image 721
Joel Avatar asked Sep 09 '11 11:09

Joel


People also ask

Is underscore js still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.

What is _ template?

The _. template() function is an inbuilt function in the Underscore. js library of JavaScript which is used to compile JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources.

How do you use underscore in JavaScript?

Adding Underscore to a Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.


1 Answers

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

like image 102
mjtognetti Avatar answered Nov 24 '22 07:11

mjtognetti