Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass JSON data into a Nunjucks template?

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.

like image 378
sjmartin Avatar asked Aug 03 '15 06:08

sjmartin


People also ask

How does Nunjucks pass data?

You can use gulp-data which allows you to pass json files to the task runner you're using to render Nunjucks.

What is a JSON template?

JSON templates allow you to control the look and feel of different pages of the online store using sections. JSON templates are data files that store a list of sections to be rendered, and their associated settings. Merchants can add, remove, and reorder these sections using the theme editor.


1 Answers

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'))
});
like image 99
yahyazini Avatar answered Oct 22 '22 23:10

yahyazini