I am looking to incorporate JSON data into nunjucks "set". Here's a simple example:
index.html
{% set divname='foo' %}
{% include 'template.nunjucks' %}
template.nunjucks
<div class="{{divname}}"></div>
Everything works smoothly. However, I want to separate the data, like the divname, from the index.html file and place it into a JSON file named data.json:
{
"div_name": "foo"
}
By using gulp-data, we can fetch the data from data.json and use {{div_name}} almost anywhere in index.html..almost. It seems that using {{div_name}} inside nunjucks content is not achievable, probably due to nested { ?
{% set divname='{{div_name}}' %}
Unable to retrieve the JSON data, the output is
<div class="{{divname}}"></div> instead of <div class="foo"></div>
The reason behind this requirement is so that in data.json, I can define multiple divnames (divname1=foo, divname2=bar, divname3=ball) and reuse template.nunjucks. This approach becomes handy when the markup in template.nunjucks or index.html gets complex, allowing the utilization of templating engines efficiently. A practical scenario is a lengthy/semi-complicated AWS CloudFormation template where resource names are employed in various instances, and different data.json files are used for dev and prod environments. Shifting values to dev-data.json and prod-data.json while keeping only one "index" file for infrastructure definition, which pulls in templates will streamline maintenance
{% set divname={{divname1}} %}
{% include 'template.nunjucks' %}
{% set divname={{divname2}} %}
{% include 'template.nunjucks' %}
dev-data.json
divname1 = dev-foo
divname2 = dev-bar
prod-data.json
divname1 = foo
divname2 = bar
There you have it, different data for dev and prod environments using a single index.html file for maintenance