Jinja2 Simple Tags
jinja2-simple-tags is a Python library that simplifies the creation of custom template tags within Jinja2 templates. It provides base classes like StandaloneTag, ContainerTag, and InclusionTag, allowing developers to extend Jinja2's functionality with Python code. The current version is 0.6.1, and it maintains an active release cadence.
Warnings
- gotcha Output from custom tags (especially StandaloneTag) is HTML-escaped by default. If your tag generates raw HTML or script that should not be escaped, you must explicitly mark it as safe.
- gotcha When using `InclusionTag`, be mindful of context inheritance. By default, it inherits the parent template's context. Explicitly manage context variables to avoid unexpected behavior or data leakage.
- gotcha Jinja2-simple-tags relies on Jinja2's parsing. Common Jinja2 `TemplateSyntaxError` issues (e.g., unclosed tags, misspelled keywords, mismatched delimiters within the custom tag's arguments or content) will still apply and can be challenging to debug.
Install
-
pip install jinja2-simple-tags
Imports
- StandaloneTag
from jinja2_simple_tags import StandaloneTag
- ContainerTag
from jinja2_simple_tags import ContainerTag
- InclusionTag
from jinja2_simple_tags import InclusionTag
Quickstart
from jinja2 import Environment
from jinja2_simple_tags import StandaloneTag
from datetime import datetime
# 1. Define your custom standalone tag
class CurrentTimeTag(StandaloneTag):
tags = {"now"}
def render(self, format_string="%Y-%m-%d %H:%M:%S"): # Renamed 'format' to 'format_string' to avoid conflict with built-in format
return datetime.now().strftime(format_string)
# 2. Set up Jinja2 Environment and load your extension
env = Environment(
extensions=[CurrentTimeTag]
)
# 3. Create a template string using your custom tag
template_content = """
<p>The current date and time is: {% now %}</p>
<p>Formatted time: {% now '%H:%M' %}</p>
"""
template = env.from_string(template_content)
# 4. Render the template
output = template.render()
print(output)