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 };
Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With