I am currently in the process of refactoring my website to speed up its generation and I came across an interesting problem: how to generate a JSON file with Nunjucks in Eleventy?
If the object contains only strings , it is really trivial. But, if you add a numeric property and you want to keep its type intact, it is still simple:
{
"name": "{{ author.name }}",
"age": {{ author.name }}
}
But, it gets complicated if you want to introduce array
properties. Effectively, if you want to have a valid JSON file, the items must be separated by a colon (,
) and it starts to look a lot more complex like in the example below:
{
{%- if collections.feed.authors -%}
"authors": [
{%- for author in collections.feed.authors %}
{
"avatar": "{{ author.avatar }}",
"name": "{{ author.name }}",
"url": "{{ author.url }}"
}
{%- if not loop.last -%},{%- endif -%}
{%- endfor %}
]
{%- endif -%}
}
It is not pretty, but it works. ๐ค
But what if you want to add a property whose value contains quotes ("
), like HTML values? Personally, I tried a lot of ideas, but none worked. ๐
{
"html": "{{ author.html }}",
"safe": "{{ author.html | safe }}"
}
I searched the Web and came across an old question on Stack Overflow which has the solution below that worked for me:
{
"html": {{ author.html | dump | safe }}
}
The combinaison of the dump and safe filters make it possible to render the value exactly as it comes from the source. For an array, this even make it possible to simplify the code for its generation if the objects are already correct:
{
{%- if authors.tags -%}
"tags": {{ authors.tags | dump | safe }}
{%- endif -%}
}
I hope this post helps you get to know the Nunjunks templating language better! ๐
Top comments (0)