0

我想在 nunjucks "set" 中使用 JSON 数据。一个最小的例子:

索引.html

{% set divname='foo' %}
{% include 'template.nunjucks' %}

模板.nunjucks

<div class="{{divname}}"></div>

效果很好。我想将数据(例如 divname)从 index.html 文件中移出到 JSON 文件中,我们将其命名为data.json

{
"div_name": "foo"
}

使用 gulp-data,我们可以读取这个 data.json 文件,并且几乎可以在 index.html 的任何地方使用 {{div_name}}。似乎不可能在 nunjucks 内容中使用 {{div_name}} ,可能是由于嵌套的 { ?

{% set divname='{{div_name}}' %}

无法提取 JSON 数据,输出为

<div class="{{divname}}"></div>   instead of   <div class="foo"></div>

想要这种行为的一个非常简单的原因是,我可以在 data.json 中定义多个 divname(divname1=foo、divname2=bar、divname3=ball),然后重用 template.nunjucks。当 template.nunjucks 或 index.html 中的标记变得非常复杂时,这是使用模板引擎强大功能的好方法。真正的用例是一个非常长/半复杂的 AWS CloudFormation 模板,其中资源名称在多个地方使用,除此之外,不同的 data.json 文件用于开发和生产环境。将值移动到 dev-data.json 和 prod-data.json,同时只为基础设施定义维护一个“索引”文件,这会引入模板将使事情更易于维护

{% set divname={{divname1}} %}
{% include 'template.nunjucks' %}
{% set divname={{divname2}} %}
{% include 'template.nunjucks' %}

开发数据.json

divname1 = dev-foo
divname2 = dev-bar

产品数据.json

divname1 = foo
divname2 = bar

瞧,dev 和 prod 的不同数据需要维护一个 index.html 文件

4

1 回答 1

3

以前从未使用过 nunjucks,但我想您可以删除语句title_data中的括号: .set{% set title = title_data %}

但是,如果您已经掌握了标题字符串,为什么还要为重新分配而烦恼。直接做模板:<title>{{ title_data }}</title>

于 2017-03-13T23:45:10.150 回答