javascript - 无法让 underscore.js 在没有语法错误的情况下使用花括号

标签 javascript templates underscore.js underscore.js-templating

有人知道为什么这行不通吗?我正在尝试让 _.template 使用大括号。

    _.templateSettings = { //change delimiter to <$ $>
          interpolate : /\<\$(.+?)\$\>/g
        };      
    var list = "<$ _.each(people, function(name) { $> <li><$ name $> </li> <$ }); $>";
    var html=_.template(list);
    console.log(html({people : ['moe', 'curly', 'larry']}));

它在 ) 处产生以下语法错误错误):

((__t=( .each(people, function(name) { ))==null?'':_t)+

Underscore 文档是这样说的:

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. You may define or omit any combination of the three. For example, to perform Mustache.js style templating:

_.templateSettings = { interpolate : /{{(.+?)}}/g };

var template = _.template("Hello {{ name }}!"); template({name : "Mustache"}); => "Hello Mustache!"

最佳答案

你的问题是插值的东西应该产生一个独立的 JavaScript 表达式,这个:

_.each(people, function(name) {

不是有效的表达式。您需要定义单独的evaluateinterpolate 正则表达式,然后将evaluate 用于_.each;像这样:

_.templateSettings = {
    interpolate: /\{\{=(.+?)\}\}/g,
    evaluate: /\{\{(.+?)\}\}/g,
};
var list = "{{_.each(people, function(name) {}} <li>{{=name}}</li> {{ }); }}";

请注意,插值现在使用 {{= ... }}{{ ... }} 仅用于评估(或嵌入)小的 JavaScript 片段。

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

关于javascript - 无法让 underscore.js 在没有语法错误的情况下使用花括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17462069/

相关文章:

c++ - 如何将模板中的纯虚方法适配到从它继承的类?

javascript - 在 AngularJS 项目中使用 Lodash 有好处吗?

javascript - 使用下划线js或lodash将对象解析为数组

c++ - 管理生命周期

javascript - 在 JavaScript 中制作一对多关系数组

javascript - Bootstrap 3 导航栏品牌标志在 FireFox 31.0 中移动导航链接

Javascript 将 Uint8Array[x] 分配给新的 var : type?

javascript - 基于另一个数组的函数构建数组

javascript - 用于在每个 URL 末尾添加参数的书签

c++ - 重载 << 使用模板 : Why am I getting the following error?