I’ve set underscore to mustache mode like so:
_.templateSettings = {
interpolate : /\{\{(.+?)\}\}/g
};
I’ve got part of a template with the following:
<script id="detail_view" type="text/template">
<% for(registration in REGISTRATION_NUMBERS){ %>
<tr>
<td>{{registration.TYPE}}</td>
<td>{{registration.VALUE}}</td>
</tr>
<% } %>
</script>
Which results in “registration not defined”. Using this causes the entire section to be output in the template. What am i doing wrong?
You have two problems, one you know about and one that you don’t.
The first problem is that you’re replacing all three
_.templateSettingswhen you only want to replace one of them. You want this:That will leave the
evaluateandescapeparts of_.templateSettingsalone. What you’re doing is the same as:so you’re ending up without an
evaluateat all. BTW, you can look at thesourceproperty of a compiled template function to see the JavaScript that your template is compiled to, the JavaScript isn’t that easy on the eyes but looking at it can help with this sort of problem.The problem you don’t know about is that a
for...inloop is for iterating over the properties of an object, not the values in an array. This means thatregistrationwill be the strings'0','1', … inside your loop and that’s not what you want. You’d need something like this in your template ifREGISTRATION_NUMBERSis an array:Or, since you have Underscore around anyway, you could use
_.each:Demo: http://jsfiddle.net/ambiguous/jfckA/