如何在lodash模板中传递对象键(带有特殊字符或空格)?

时间:2016-06-16 09:08:20

标签: javascript lodash

我们可以像

这样的模板中的键传递数组
var compiled = _.template('<%= [hello] %>')({ 'hello': 'how are you'});
console.log(compiled);// how are you

或者像对象键

var compiled = _.template('<%= hello %>')({ 'hello': 'how are you' });

console.log(compiled);//how are you

如何传递一些特殊字符的键名?

var compiled = _.template("<%= ['hell:-o'] %>")({ 'hell:-o': 'how are you' });

和多维数组一样?

var compiled = _.template("<%= [hello][hello] %>")({ 'hello': {'hello': 'how are you'} }); 

1 个答案:

答案 0 :(得分:1)

默认情况下,整个对象在模板中以obj的形式提供,因此你可以这样做#3:

> _.template("<%= obj['hell:-o'] %>")({ 'hell:-o': 'how are you' });
"how are you"

您甚至可以更改docs

中提到的此变量的名称
_.template("<%= data['hell:-o'] %>", {variable: "data"})({ 'hell:-o': 'how are you' });
"how are you"

对于#4,您可以像在JS中一样访问它:

> _.template("<%= hello.hello %>")({ 'hello': {'hello': 'how are you'} }); 
"how are you"