Domanda

I was just wondering how you use the underscore templates in a .aspx view since the <%= %> tags that underscore uses get picked up by the .aspx rendering engine and give me errors.

For instance:

<script type="text/template" id="my-template">
  <span class="event" title="<%= description %>">
      <%= title %>
  </span>
</script>

This template gives me an error since the .aspx rendering engine thinks I'm trying to bind this stuff to the Model.

Thanks.

È stato utile?

Soluzione

From the fine manual:

template _.template(templateString, [data], [settings])
[...]
If ERB-style delimiters aren't your cup of tea, you can change Underscore's template settings to use different symbols to set off interpolated code. Define an interpolate regex to match expressions that should be interpolated verbatim, an escape regex to match expressions that should be inserted after being HTML escaped, and an evaluate regex to match expressions that should be evaluated without insertion into the resulting string.

So if the default <%=...%>, <%-...%>, and <%...%> delimiters aren't working for you then you can use different ones with a simple configuration change. For example, if you wanted to use {%...%} instead of <%...%>, then do this after underscore.js is loaded and before you use _.template:

_.templateSettings = {
    interpolate: /\{%=(.+?)%\}/g,
    escape:      /\{%-(.+?)%\}/g,
    evaluate:    /\{%(.+?)%\}/g
};

Demo: http://jsfiddle.net/ambiguous/TfB5M/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top