DEV Community

Luke Harris
Luke Harris

Posted on • Originally published at lkhrs.com on

1

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

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (1)

Collapse
 
fenix profile image
Fenix

thX for sharing !

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay