nunjucks中的JSON数据模板化,使用gulp-data

时间:2017-03-13 22:14:06

标签: javascript json nunjucks gulp-data gulp-nunjucks-render

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

的index.html

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

template.nunjucks

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

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

{
"div_name": "foo"
}

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

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

无法提取JSON数据,输出为

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

想要这种行为的一个非常简单的原因是,在data.json中我可以定义多个divnames(divname1 = foo,divname2 = bar,divname3 = ball),然后重用template.nunjucks。当template.nunjucks或index.html中的标记变得非常复杂时,这是一种使用模板引擎的强大方法。真实用例是一个非常长/半复杂的AWS CloudFormation模板,其中资源名称在多个位置使用,并且除此之外,不同的data.json文件用于dev和prod环境。将值移动到dev-data.json和prod-data.json,同时只保留一个&#34;索引&#34;基础架构定义的文件,其中提取模板将使事情更易于维护

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

DEV-data.json

divname1 = dev-foo
divname2 = dev-bar

PROD-data.json

divname1 = foo
divname2 = bar

Voila,dev和prod的不同数据,只保留一个index.html文件

1 个答案:

答案 0 :(得分:3)

以前从未使用过nunjucks,但我想你可以删除Error: Failed to generate Policyfile.lock Reason: (CookbookOmnifetch::GitCommandError) Git error: command `git reset --hard 7e5e4bccf57718cacc246f1b4d501ff7de8ac13d` failed. If this error persists, try removing the cache directory at 'C:/Users/pcummuskey/AppData/Local/chefdk/cache/.cache/git/780b7dbee933c3a9efbfd3898d54cdf72784fa7e'.Output from the command: error: unable to create file test/kitchen/.kitchen/tmp/librarian/cache/source/chef/site/877777683730772c36b1e6a3fc3aa2c3/windows/version-uri/a3432e93fb3c21cb7111fde71e435661/package/files/default/handlers/windows_reboot_handler.rb: Filename too long Checking out files: 100% (389/389), done. fatal: Could not reset index file to revision '7e5e4bccf57718cacc246f1b4d501ff7de8ac13d'. 语句中title_data周围的括号:set

但是如果你已经有了标题字符串的句柄,那么为什么还要麻烦重新分配。只需直接模板:{% set title = title_data %}

相关问题