Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 692
Mike Christensen Avatar asked Mar 15 '12 17:03

Mike Christensen


1 Answers

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 &lt;script&gt;

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

like image 123
tkone Avatar answered Sep 23 '22 12:09

tkone