【发布时间】:2015-08-03 06:18:42
【问题描述】:
我想使用 Nunjucks 模板,但想传入我自己的 JSON 数据以用于模板。
这里的文档很少。
https://mozilla.github.io/nunjucks/templating.html
谢谢。
【问题讨论】:
-
参见 Nunjucks 问题中的 Passing data to includes
我想使用 Nunjucks 模板,但想传入我自己的 JSON 数据以用于模板。
这里的文档很少。
https://mozilla.github.io/nunjucks/templating.html
谢谢。
【问题讨论】:
您可以使用gulp-data 它允许您将 json 文件传递给用于渲染 Nunjucks 的任务运行器。
gulp.task('nunjucks', function() {
return gulp.src('app/pages/**/*.+(html|nunjucks)')
// Adding data to Nunjucks
.pipe(data(function() {
return require('./app/data.json')
}))
.pipe(nunjucksRender({
path: ['app/templates']
}))
.pipe(gulp.dest('app'))
});
【讨论】:
只需结合使用dump 和safe 过滤器:
<script>
const choices = {{ yourJsonVar | dump | safe }};
</script>
【讨论】:
2019 年在这里找到了这颗宝石,但认为它对像我这样搜索过但没有找到任何东西的人会有所帮助。
首先,在宏中创建一个带有预期参数的模板部分
{% macro render(secTitle, secSubtitle) %}
<h4 class="heading">
{{ secTitle | safe }}, {{ secSubtitle | safe }}
</h4>
{% endmacro %}
另存为[yourname].tpl - 在本例中为heading.tpl
然后,导入此块并使用上面宏中指定的函数(本例中为render())
{% block heading %}
{% import "components/heading.tpl" as heading with context %}
{{ heading.render(
secTitle='Hello there',
secSubtitle='General Kenobi'
) }}
{% endblock %}
这将导致:
<h4 class="heading">
Hello there, General Kenobi
</h4>
请注意组件中字符串后面的| safe - 这意味着它将以 HTML 格式输出字符串(例如,<br> 将创建一个新行,而不是在文本中输出 <br>)。
【讨论】:
您可以使用他们的异步渲染来实现这一点。
https://mozilla.github.io/nunjucks/api.html#render
$.getJSON('/path/to/file.json', function (result) {
nunjucks.render('path/to/template/file.html', { result : result }, function (err, res) {
// do something
});
});
【讨论】:
[object Object]。