ryanhornberger / nunjucks-html-loader

Webpack Loader for Nunjucks that returns raw html. Also works with Webpack watching system.
MIT License
27 stars 23 forks source link

How pass data #8

Closed romanmarkelov closed 7 years ago

romanmarkelov commented 7 years ago

How pass data, for example: global.json and then use in tpl

ginaldoterencio commented 7 years ago

Hi @webmarkelov!

There is a loader param named context. You can use it to pass data into a template.

Inside the webpack.config.js

First create the nunjucks querystring:

const sourceDir = path.join(__dirname, '../src/');

const nunjucksConfig = JSON.stringify({
  'searchPaths': [sourceDir],
  'context': require(sourceDir + 'data/index.js')
});

Then use the querystring in the loader as so:

{
    include: /\.(njk|nunjucks)$/,
    // Here we are using the nunjucks config variable created before
    use: ['html-loader', 'nunjucks-html-loader?' + nunjucksConfig]
}

Finally create the index.js file inside the data folder located at sourceDir, with the content as follow:

const site = require('./site.json');

module.exports = {
  site
};

[]'s

jeremyzahner commented 7 years ago

Thanks @ginaldoterencio for the explanation.

@webmarkelov I'll close the issue for now. Feel free to reopen it if the directions @ginaldoterencio gave you do not work for your case.