Import a Jinja Macro & Use in For Loop
Here's how to import a Jinja macro and use it in a for loop. We're going to do it all! Work, Jinja, work!
Define Macro
A macro is nice, because you have a template-ready function to reuse. Let's say that we want a macro that will insert nice svg icons for us. It'll take a name
parameter out return svg markup.
We'll create a macros.html
file and define it like so:
{% macro icon(name, size='1.5rem') %}
<span class="icon" style="width:{{size}};height:{{size}};">
{% include "icon-" ~ name ~ ".html" %}
</span>
{% endmacro %}
Only relating to this exact example, we'll create an icon svg file too, in icon-wow.html
:
<svg xmlns="http://www.w3.org/2000/svg">
<path d="M2 20.575V5c0-.55.196-1.021.588-1.413A1.925 1.925 0 0 1 4 3h16c.55 0 1.021.196 1.413.587.391.392.587.863.587 1.413v12c0 .55-.196 1.021-.587 1.413A1.928 1.928 0 0 1 20 19H6l-2.3 2.3c-.317.317-.68.387-1.088.212-.408-.175-.612-.487-.612-.937Zm2-2.4L5.175 17H20V5H4v13.175Z" />
</svg>
Import the Macro
That macro is defined in a file for utils and things. But we want to import it into our main page template. At the top of our page template (maybe called home.html
), we can import it with:
{% from "macros.html" import icon %}
Now we can reference the icon
macro.
Use the Macro in a Loop
Let's say that we passed a context object into our template that included links
:
render('home.html', {
links: [
{ icon: 'wow': href: '/wow' },
{ icon: 'cool': href: '/cool' },
{ icon: 'rad': href: '/rad' }
]
})
To render those in the template, we might write:
{% for link in links %}
<a href={{link.href}}>
{{icon(link.icon)}}
</a>
{% endfor %}
We render in a loop. We use {{double curlies}}
around the icon()
call. But we're already in double curlies, so we don't nest those, adding more curlies around the link.icon
argument.
And there we go!: Macro defined, imported, used. Bed.