我想使用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'))
});
Run Code Online (Sandbox Code Playgroud)
只需使用dump和safe过滤器组合即可:
<script>
const choices = {{ yourJsonVar | dump | safe }};
</script>
Run Code Online (Sandbox Code Playgroud)
您可以使用他们的异步渲染来实现这一点。
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
});
});
Run Code Online (Sandbox Code Playgroud)