Jinja2 Simple Tags

0.6.1 · active · verified Fri Apr 10

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

Install

Imports

Quickstart

This quickstart demonstrates how to define a simple custom tag using StandaloneTag, register it with a Jinja2 environment, and render a template that uses the new tag to display the current time. Remember to pass your custom tag class to the `extensions` list of the Jinja2 Environment.

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)

view raw JSON →