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.
pip install jinja2-simple-tagsVerified import paths — ran on the pinned version, not inferred.
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.
Set `safe_output = True` as a class attribute on your tag class, or return a `jinja2.Markup` object from your `render` method.
The `get_context()` method allows you to merge additional context variables. Understand Jinja2's context behavior (e.g., `with context` or `without context` in `include` statements) when designing your inclusion tags.
Carefully review your template syntax and the arguments passed to your custom tags. Enable Jinja2's strict undefined behavior for earlier detection of missing variables during development (`Environment(undefined=StrictUndefined)`).
pip install jinja2-simple-tags
pip install Jinja2
Ensure your custom tag class is added to the Jinja2 environment's extensions. Example: `env = Environment(extensions=[MyCustomTagExtension])` or `env.add_extension(MyCustomTagExtension)`.
Check if the variable or its attribute exists before trying to access it, for example, using an `if` condition: `{% if my_object and my_object.some_attribute %}{{ my_object.some_attribute }}{% endif %}` or by providing a default value: `{{ my_object.some_attribute | default('N/A') }}`.