Snippets are common blocks of HTML or text that can be used globally across all templates. Some clever uses included:
- Reusing Common headers and footers across templates
- Reusing Common CSS
- Keeping a “library” of jinja macros to be reused throughout templates
How do I use snippets?
Create a snippet in the Snippets) section.
In your template, reference the snippet by snippet name in the template:
{% snippet "A Snippet" %}
Can I use snippets within snippets?
Yes! Nested snippets are supported.
Can variables be used in snippets?
Yes! All data that can be referenced in a template can be referenced in a snippet. For example:
Snippet - Link
<a href="{{ link }}">Click Here</a>
Template
{% snippet "Link" %}
Can snippets be given variables like a function?
Snippets don’t take variables. It’s better to use a jinja macro to accomplish that.
Jinja Macro Example
Jinja macros are similar to functions in programming languages. They abstract a block of commonly used code and can be set up to accept modifications when called.
Snippet - Macro Example
{% macro button(text, url, color='#49a9ce') %}
<div>
<!--[if mso]>
<v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="{{ url }}" style="height:53px;v-text-anchor:middle;width:150px;" arcsize="48%" stroke="f" fillcolor="{{ color }}">
<w:anchorlock/>
<center>
<![endif]-->
<a href="{{ url }}"
style="background-color:{{ color }};border-radius:25px;color:#ffffff;display:inline-block;font-family:sans-serif;font-size:13px;font-weight:bold;line-height:53px;text-align:center;text-decoration:none;width:150px;-webkit-text-size-adjust:none;">
{{ text }}
</a>
<!--[if mso]>
</center>
</v:roundrect>
<![endif]-->
</div>
{% endmacro %}
Template
{# Import the Snippet with the Macro #}
{% snippet "Macro Example" %}
{# Use the Macro in the template #}
{{ button('we made a macro!', 'https://www.example.com', color="#e91e63") }}
For more information on Jinja Macros and other examples, visit the official Jinja documentation.