asp.net-mvc - 如何在 ASP.Net MVC View 中使用下划线/javascript 模板

标签 asp.net-mvc underscore.js underscore.js-templating

我只是想知道如何在 .aspx View 中使用下划线模板,因为下划线使用的 <%= %> 标记会被 .aspx 渲染引擎拾取并给我错误。

例如:

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

这个模板给了我一个错误,因为 .aspx 渲染引擎认为我正在尝试将这些东西绑定(bind)到模型。

谢谢。

最佳答案

来自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.

所以如果默认<%=...%> , <%-...%> ,和<%...%>分隔符不适合您,那么您可以通过简单的配置更改来使用不同的分隔符。例如,如果您想使用 {%...%}而不是<%...%> ,然后在 underscore.js 之后执行此操作已加载并在您使用 _.template 之前:

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

演示:http://jsfiddle.net/ambiguous/TfB5M/

关于asp.net-mvc - 如何在 ASP.Net MVC View 中使用下划线/javascript 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16016316/

相关文章:

templates - 升级到 underscore 1.7 时出现模板错误

c# - 使用 ResolveUnregisteredType 事件在 Simple Injector 中注入(inject)可能会根据请求更改的数据库配置值

c# - 使用 MVC 和 Razor 在 div 中放置一个 css 类

javascript - 停止集合对自身进行排序,但仍然能够对 i 进行排序

javascript - 模板无法使用 Backbone.js 加载

javascript - 在解析中使用第三方库进行云代码时出现ReferenceError

c# - 将任何字段前缀绑定(bind)到 C# MVC 4/5 中的操作参数

c# - ASP.NET Core 2.0 无法检查用户是否在 Razor View 或 Controller [authorize] 注释中正确扮演角色

javascript - 在 Javascript 中创建数组数组

javascript - Underscore.js _.template 导致 Chrome 扩展出错