How can I pass JSON data into a Nunjucks template?

2019-04-21 17:57发布

I want to use Nunjucks templates but want to pass in my own JSON data to be used on the templates.

The documentation here is pretty sparse.

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

Thank you.

2条回答
狗以群分
2楼-- · 2019-04-21 18:50

You can use gulp-data which allows you to pass json files to the task runner you're using to render 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'))
});
查看更多
你好瞎i
3楼-- · 2019-04-21 19:00

You can use their async render to achieve that.

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
        });
    });
查看更多
登录 后发表回答