如何将JSON数据传递到Nunjucks模板?

sjm*_*tin 10 jinja2 nunjucks

我想使用Nunjucks模板但想要传递我自己的JSON数据以在模板上使用.

这里的文档很稀疏.

https://mozilla.github.io/nunjucks/templating.html

谢谢.

yah*_*ini 9

您可以使用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)


bry*_*dar 7

只需使用dump和safe过滤器组合即可:

<script>
  const choices = {{ yourJsonVar | dump | safe }};
</script>
Run Code Online (Sandbox Code Playgroud)


Mub*_*tab 0

您可以使用他们的异步渲染来实现这一点。

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)