在下划线模板中使用整数变量作为键

Using integer variable as key in underscore template

根据下划线的 documentation,它允许你像下面那样做字符串 template/interpolation:

var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'});
// => "hello: moe"

不用像"name"那样的变量符号,不知道有没有办法用整型作为key?例如:

var compiled = _.template("hello: <%= 1 %>");
compiled({"1": 'moe'});
// => "hello: moe"

我尝试了一下,但 underscorejs 模板将其评估为文字而不是变量,如果提供的变量中包含这样的整数键,是否有任何方法可以使用下划线进行模板化?谢谢。

不,你不能使用整数,你必须使用一个有效的变量名称,这意味着它可以有一个整数但不能只有一个整数。

有效的是:

compiled = _.template("hello: <%= a1 %>");
console.log(compiled({a1: 'moe'}));

compiled = _.template("hello: <%= _1 %>");
console.log(compiled({_1: 'moe'}));


compiled = _.template("hello: <%= a %>");
console.log(compiled({a: 'moe'}));

http://jsfiddle.net/BwHxv/309/