how do I access json from gulp data in nunjucks?

I have a some.json file like this:

{
  "disneyland-paris": {
    "lang": "de"
  },
  "hanoi": {
    "lang": "de"
  }
}

… that I want to get into a nunjucks template with:

pipe(data(function() {
  return JSON.parse(fs.readFileSync(".../some.json"))
}))
.pipe(nunjucksRender())

How would I access this data within nunjucks?

This does not work:

{{ some }}

or

{{ some.json }}

One of many approaches you could take is use gulp nunjucks render for your gulp project. If you decide to go this route, you can use the following steps as a proof-of-concept to achieve your goal. And if not, you can borrow ideas from the following steps anyway!

  • Step 1 - Within your project, "you could" structure your JSON data like so in a file called Languages.js :
const languages = [
  {
    "group": [{
      "location":"disenyland-paris",
      "lang": "de"
    },
    {
      "location":"hanoi",
      "lang": "de"
    },
  ]
}];

module.exports = languages;
  • Step 2 - From your gulpfile.js, assuming you are running a gulp project, call your JSON data, then reference it within your Nunjucks logic as an environmental global...
...

const nunjucksRender = require('gulp-nunjucks-render');
const Languages = require('./src/models/Languages');

...

const manageEnvironment = function (environment) {
    environment.addGlobal('mLangauges',Languages);
}

...

function genNunJucks(cb) {
    return src(['src/views/*.html'])
        .pipe(nunjucksRender({
            path: ['src/views/', 'src/views/parts'], // String or Array
            ext: '.html',
            inheritExtension: false,
            envOptions: {
                watch: true,
            },
            manageEnv: manageEnvironment,
            loaders: null
        }))
        .pipe(dest('pub')); //the final destination of your public pages
    cb();
}

//then do more stuff to get genNunJucks() ready for gulp commands...

  • Step 3 - From within your Nunjucks template file, call the data like so...
   {% for sections in mLangauges %}
      {% for mgroup in sections.group %}
         <p>{{mgroup.location}}</p>
         <p>{{mgroup.lang}}</p>
      {% endfor %}
   {% endfor %}

All that is left to do is run your gulp project :)

Tip - If you change your JSON data while working, you may need to re-build your gulp project to see the udpated JSON data on your web page. Re-building can be as simple as running 'npm run build' if you set it up right in your package.json file.