DEV Community

Luke Harris
Luke Harris

Posted on • Originally published at lkhrs.com on

Using variables in Jinja include statements

I’m working on a project that uses Pelican as the static site generator. Pelican uses the Jinja templating language, which looks similar to Liquid and Nunjucks.

Inside a for loop, I have a set of SVGs that I need to match to a variable in the frontmatter for each page, with the SVG code itself in the HTML output. I can’t use <img> here, because I need to set the fill color for the SVGs with CSS.

I tried to use the include tag like this:

{%- include icons/{{ variable }}.svg -%}

Enter fullscreen mode Exit fullscreen mode

…which didn’t work, and led to a lot of time spent trying other methods, like writing a macro for each icon with an if statement chain worthy of TheDailyWTF, dictionary comparison, and other complicated nonsense.

After reading the docs for the 10th time, I happened to scroll down to the section on Other Operators:

~ (tilde) Converts all operands into strings and concatenates them.

{{ "Hello " ~ name ~ "!" }} would return (assuming name is set to ‘John’) Hello John!.

And came up with this elegant solution:

{%- include "icons/"~ variable ~".svg" ignore missing -%}

Enter fullscreen mode Exit fullscreen mode

Boom!

ignore missing tells the templating engine to continue when variable isn’t set.

Here’s the full loop:

{% for p in pages %}
  <li>
    <a href="{{ SITEURL }}/{{ p.url }}">
      {%- include "icons/"~ p.icon ~".svg" ignore missing -%}
      {{ p.title }}
    </a>
  </li>
{% endfor %}

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
fenix profile image
Fenix

thX for sharing !