是否可以在Nunjucks变量中使用包含句点的属性名称



当我尝试通过renderString():在以下javascript对象上下文上呈现Nujucks字符串:Greeting: {{ bar.text }}

const foo = {
'bar.text': 'Hello world'
}

我收到以下输出:Template render error: attempted to output null or undefined value。当我删除句点时,这个问题就解决了。

在Nunjucks中渲染模板时,是否可以使用包含句点的字符串属性?

{{ bar.text }}表示您拥有bar-对象和text-道具。所以我看到了两种解决方法。

  1. 使用对象
const foo = {
bar: {text: 'Hello world'}
}
  1. 添加过滤器/全局函数以通过字符串bar.text获取值
var nunjucks  = require('nunjucks');
var env = nunjucks.configure();
env.addFilter('context', function(variable) {
return this.ctx[variable];
});
var html = env.renderString(`{{ 'bar.text' | context }}`, {'bar.text': 'Hello-world'});
console.log(html);

最新更新