JSON data in nunjucks templating, using gulp-data

1.3k views Asked by At

I would like to use JSON data inside of nunjucks "set". A minimal example:

index.html

{% set divname='foo' %}
{% include 'template.nunjucks' %}

template.nunjucks

<div class="{{divname}}"></div>

Which works great. I would like to move data, for example the divname, out of the index.html file and into a JSON file, lets name it data.json:

{
"div_name": "foo"
}

Using gulp-data, we can read this data.json file and use {{div_name}} almost anywhere in index.html..almost. It doesn't seem possible to use {{div_name}} inside of nunjucks content, likely due to nested { ?

{% set divname='{{div_name}}' %}

fails to pull in the JSON data, the output is

<div class="{{divname}}"></div>   instead of   <div class="foo"></div>

A very simplified reason for wanting this behavior is so that in data.json I can define multiple divnames (divname1=foo, divname2=bar, divname3=ball) and then reuse template.nunjucks. When the markup in template.nunjucks or index.html becomes very complicated, this is a great way to use the power of templating engines. The real use case is a very long/semi-complicated AWS CloudFormation template where resource names are used in multiple places, and on top of that different data.json files are used for dev and prod environments. Moving values to dev-data.json and prod-data.json while maintaining only one "index" file for the infrastructure definition, which pulls in templates will make things much more maintainable

{% 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

Voila, different data for dev and prod with one single index.html file to maintain

1

There are 1 answers

1
Luke Chinworth On BEST ANSWER

Never used nunjucks before, but I imagine you could remove the brackets around title_data in theset statement: {% set title = title_data %}.

But why even bother with the reassignment if you already have a handle on the title string. Just template it directly: <title>{{ title_data }}</title>