mozilla / nunjucks

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)
https://mozilla.github.io/nunjucks/
BSD 2-Clause "Simplified" License
8.52k stars 637 forks source link

json data to index.nunjucks #949

Open fernandofas opened 7 years ago

fernandofas commented 7 years ago

Hello all,

After read a lot about it , I still didn't find the right way to pass data from a json file to my index.nunjucks. I tried include and render and nothing works.

If anyone could clarify this simple task it will be great.

json to index.nunjucks file

Thank you all in advance.

Kind regards,

Fernando Fas

sudhirbeldar commented 7 years ago

Hey Fernandofas,

Me too new to nunjucks, but did some work till date.

I hope below code will work for you. In below example, I have kept static json data. In your case you can store json data in any variable and render index.nunjucks passing that variable.

var express = require( 'express' ) ; var nunjucks = require( 'nunjucks' ) ; var app = express() ; app.get( '/', function( req, res ) { var jsondata = { firstName: "Sudhir", lastName: "Beldar" }; return res.render('index.njk', {data:jsondata}) ;

res.render('index.njk', {data: jsondata})

});

fernandofas commented 7 years ago

Hi sudhirbeldar,

Did u place the codes inside the gulpfile.js or in the json file?

Thank you.

sudhirbeldar commented 7 years ago

This code will be in .js file and not in json.

fernandofas commented 7 years ago

I try that, still not working. I might be missing something there. Gonna try again later. Thank you sudhirbeldar.

ArmorDarks commented 7 years ago

Nunjucks doesn't have native way to read and serialize json files. You should read file and serialize it in environment, where you're invoking Nunjucks. Then you should pass that file to renderer of Nunjucks as context.

Alternatively, you can write a Nunjucks filter (or a global) which will read needed file and expose it as object to Nunjucks, and add that filter/global to to Nunjucks env with addFilter.