I've been comparing different JavaScript template engines to see which one gives me the best performance for large sets of data. One that I ran across is Underscore.js. However, I haven't been able to get any of the examples working. My template looks like:
<% _.each(projects(), function(project) { %>
<tr>
<td><%= project.code %></td>
<td><%= project.request %></td>
<td><%= project.stage %></td>
<td><%= project.type %></td>
<td><%= project.launch %></td>
</tr>
<% }) %>
However, when I run the page I get a server-side ASP.NET exception, as it's trying to compile the text within the <% ... %>
tags:
Compiler Error Message: CS1026: ) expected
Line 826: <% _.each(projects(), function(project) { %>
I was unable to find a way to escape these tags, nor was I able to find a way to configure Underscore to use a different syntax. Is there a workaround, or are Underscore and ASP.NET simply incompatible with each other?
Same issue with JSP, so we do this:
_.templateSettings = {interpolate : /\{\{(.+?)\}\}/g, // print value: {{ value_name }}
evaluate : /\{%([\s\S]+?)%\}/g, // excute code: {% code_to_execute %}
escape : /\{%-([\s\S]+?)%\}/g}; // excape HTML: {%- <script> %} prints <script>
This will allow you to use all the various versions of the tag outputs: interpolation, evaluation and escaping.
<%
are tags used by asp.net. So when the page is parsed, it tries to interpret those but asp.net does not understand the syntax as it expects C# code, not javascript.
You can change the interpolation symbols in the templateSettings to something like { }
and {{ }}
_.templateSettings = {
interpolate : /\{\{(.+?)\}\}/g
evaluate : /\{(.+?)\}/g;
};
var template = _.template("Hello {{ name }}!");
template({name : "Mustache"});
=> "Hello Mustache!"
Documentation
FYI, these are the default settings:
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};