Using Underscore.js with ASP.NET

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Same issue with JSP, so we do this:

_.templateSettings = {interpolate : /{{(.+?)}}/g,      // print value: {{ value_name }}
                      evaluate    : /{%([sS]+?)%}/g,   // excute code: {% code_to_execute %}
                      escape      : /{%-([sS]+?)%}/g}; // excape HTML: {%- <script> %} prints &lt;script&gt;

This will allow you to use all the various versions of the tag outputs: interpolation, evaluation and escaping.

Method 2

<% 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    : /<%([sS]+?)%>/g,
  interpolate : /<%=([sS]+?)%>/g,
  escape      : /<%-([sS]+?)%>/g
};

Method 3

replace:

<% }) %>

change for:

<% }); %>

good luck!!!


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x