Is there a way to set data dynamically ?
gterras opened this issue · 2 comments
gterras commented
Hi,
Thanks for the nice plugin. I was wondering if there was a way to inject dynamic data to the template? Right now having to use a predefined config file make it really difficult (unless I'm missing something).
.nunjucksrc
{
root: ".",
data: { foo : "bar"}
}
What if I want to inject a foo2
prop inside a specific template ? This is working :
index.html.njk
...
{% set foo2 = 'bar2' %}
{{ foo2 }}
but this is not :
index.html.njk
...
{% set foo2 = 'bar2' %}
<script src="./script.js.njk" ></script>
script.js.njk
{{ foo2 }}
// Output nothing
The only solution I am considering right now is to fs.writeFile
the .nunjucksrc
, is there better to do ?
Thank you !
chocolateboy commented
.nunjucksrc
is for static data (JSON). If you want dynamic data, you'll need to use a JS file, e.g.:
$ cat nunjucks.config.js
module.exports = {
data ({ filename }) {
if (filename === 'script.js.njk') {
return { foo2: 'whatever' }
} else {
return { foo: 'bar' }
}
}
}
gterras commented
Ok right I missed this example in the doc, thanks 👍