How to use underscore/javascript templates in ASP.Net MVC views

给你一囗甜甜゛ 提交于 2019-12-02 00:04:29

问题


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.


回答1:


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/



来源:https://stackoverflow.com/questions/16016316/how-to-use-underscore-javascript-templates-in-asp-net-mvc-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!