Concatenate strings in Nunjucks

24 Apr 2021 in TIL

Spoiler: It involves using an array of strings and the `join` filter

I recently needed to dynamically create a URL using nunjucks.

My first attempt was to use string interpolation:

{% set url = "/bits/{{ data.slug }}" %}

This didn't work.

It turns out that to build a string from multiple parts, you should use an array and the join filter:

{% set url = ["/bits/", data.slug] | join %}

This worked as intended