### Install Gettext Translations during Environment Creation
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/extensions.md
Provides an example of how to install gettext translations directly when creating a Jinja Environment, combining extension loading and translation setup in one step.
```python
from jinja2 import Environment
# Assuming 'get_gettext_translations()' returns a translation object
# translations = get_gettext_translations()
# env = Environment(extensions=["jinja2.ext.i18n"])
# env.install_gettext_translations(translations)
```
--------------------------------
### Environment Setup and Template Loading
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/api.md
Demonstrates how to create a Jinja Environment with a PackageLoader and load a template.
```APIDOC
## Environment Setup and Template Loading
### Description
This section covers the basic setup of a Jinja Environment, including configuration and loading templates from a package. It's the primary way applications interact with Jinja.
### Method
N/A (Code Example)
### Endpoint
N/A (Code Example)
### Parameters
N/A
### Request Example
```python
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader("yourapp"),
autoescape=select_autoescape()
)
template = env.get_template("mytemplate.html")
print(template.render(the="variables", go="here"))
```
### Response
#### Success Response (200)
N/A (Code Example)
#### Response Example
```
(Output of template rendering)
```
```
--------------------------------
### Jinja BaseLoader and Custom Loader Example
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/api.md
Demonstrates the creation of a custom file system loader in Jinja by subclassing `BaseLoader`. This example shows how to implement the `get_source` method to read template content from a specified directory and handle `TemplateNotFound` exceptions.
```python
from jinja2 import BaseLoader, TemplateNotFound
from os.path import join, exists, getmtime
class MyLoader(BaseLoader):
def __init__(self, path):
self.path = path
def get_source(self, environment, template):
path = join(self.path, template)
if not exists(path):
raise TemplateNotFound(template)
mtime = getmtime(path)
with open(path) as f:
source = f.read()
return source, path, lambda: mtime == getmtime(path)
```
--------------------------------
### Jinja Nested Template Inheritance Example
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
Provides an example of nested template inheritance in Jinja, showing how 'super()' calls can be chained to access blocks from different levels of the inheritance tree.
```jinja
# parent.tmpl
body: {% block body %}Hi from parent.{% endblock %}
# child.tmpl
{% extends "parent.tmpl" %}
{% block body %}Hi from child. {{ super() }}{% endblock %}
# grandchild1.tmpl
{% extends "child.tmpl" %}
{% block body %}Hi from grandchild1.{% endblock %}
# grandchild2.tmpl
{% extends "child.tmpl" %}
{% block body %}Hi from grandchild2. {{ super.super() }} {% endblock %}
```
--------------------------------
### Configure Jinja Environment with Cache Extension
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/extensions.md
This example shows how to configure a Jinja Environment to use the custom FragmentCacheExtension and integrate it with a cache backend like cachelib.SimpleCache. This setup allows the 'cache' tag to function within Jinja templates.
```python
from jinja2 import Environment
from cachelib import SimpleCache
env = Environment(extensions=[FragmentCacheExtension])
env.fragment_cache = SimpleCache()
```
--------------------------------
### Initialize FileSystemBytecodeCache
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/api.md
This example shows how to instantiate the FileSystemBytecodeCache in Python. It allows specifying a directory for cache files and a pattern for naming them. If no directory is provided, a default location is used.
```python
from jinja2.bccache import FileSystemBytecodeCache
bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')
```
--------------------------------
### Install Gettext Translations for i18n Extension
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/extensions.md
Shows how to install translation functions for the i18n extension. This includes methods for installing global translations, null translations (no-op), specific callable functions, and uninstalling translations.
```python
from jinja2 import Environment
# Assuming 'translations' is an object implementing gettext, ngettext, etc.
# Example: translations = get_gettext_translations()
# Install global translations
# env.install_gettext_translations(translations)
# Install null translations (no-op)
# env.install_null_translations()
# Install specific callable functions
# env.install_gettext_callables(gettext_func, ngettext_func)
# Uninstall translations
# env.uninstall_gettext_translations()
```
--------------------------------
### Install Jinja2 using pip
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/intro.md
This command installs the latest version of the Jinja2 templating engine using pip. It is recommended to use a virtual environment for project dependency isolation. Jinja2 requires Python 3.10 or newer.
```text
$ pip install Jinja2
```
--------------------------------
### Jinja Basic For Loop Example
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
Demonstrates a basic for loop in Jinja to iterate over a sequence and render list items. This is a fundamental Jinja construct for dynamic content generation.
```jinja
# for item in seq:
{{ item }}
# endfor
```
--------------------------------
### Initialize FileSystemLoader with multiple search paths
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/api.md
This example shows how to configure a `FileSystemLoader` to search for templates across multiple directories. Jinja will check these directories in the order they are provided, stopping at the first match found.
```python
from jinja2 import FileSystemLoader
loader = FileSystemLoader(["/override/templates", "/default/templates"])
```
--------------------------------
### Jinja Template Example
Source: https://github.com/fahreddinozcan/jinja/blob/main/README.md
This snippet demonstrates basic Jinja template syntax, including template inheritance, block definition, and a for loop to iterate over a list of users. It showcases how to structure an HTML document with dynamic content.
```jinja
{% extends "base.html" %}
{% block title %}Members{% endblock %}
{% block content %}
{% endblock %}
```
--------------------------------
### Jinja2 Environment Setup and Basic Rendering in Python
Source: https://context7.com/fahreddinozcan/jinja/llms.txt
Demonstrates how to set up a Jinja2 Environment with a FileSystemLoader, configure autoescaping and whitespace control, load and render templates, create templates from strings, and add custom filters and tests.
```python
from jinja2 import Environment, FileSystemLoader, select_autoescape
# Create environment with filesystem loader
env = Environment(
loader=FileSystemLoader('templates'),
autoescape=select_autoescape(['html', 'xml']),
trim_blocks=True,
lstrip_blocks=True
)
# Load and render a template
template = env.get_template('index.html')
output = template.render(
title='Welcome',
users=[{'name': 'Alice', 'email': 'alice@example.com'},
{'name': 'Bob', 'email': 'bob@example.com'}]
)
print(output)
# Create template from string
template = env.from_string('Hello {{ name }}!')
print(template.render(name='World'))
# Output: Hello World!
# Add custom filter
def reverse_filter(s):
return s[::-1]
env.filters['reverse'] = reverse_filter
template = env.from_string('{{ "hello"|reverse }}')
print(template.render())
# Output: olleh
# Add custom test
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
env.tests['prime'] = is_prime
template = env.from_string('{% if 7 is prime %}Prime{% endif %}')
print(template.render())
# Output: Prime
```
--------------------------------
### Jinja Macro Call Example
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
Shows how to call a previously defined Jinja macro, `input`, to generate HTML form elements. It demonstrates passing different arguments to customize the generated input fields.
```html+jinja
{{ input('username') }}
{{ input('password', type='password') }}
```
--------------------------------
### Recommended Autoescaping Setup with PackageLoader
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/api.md
This is a recommended configuration for Jinja2 that enables autoescaping for templates ending in '.html', '.htm', and '.xml'. It uses select_autoescape to define the enabled extensions and PackageLoader for loading templates from a package.
```python
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(autoescape=select_autoescape(['html', 'htm', 'xml']),
loader=PackageLoader('mypackage'))
```
--------------------------------
### Jinja Macro with Call Block Example
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
Demonstrates how to define a Jinja macro that accepts a caller function and how to invoke it using the 'call' block. This allows for dynamic content injection into macro-defined structures.
```html+jinja
{% macro render_dialog(title, class='dialog') -%}
{{ title }}
{{ caller() }}
{%- endmacro %}
{% call render_dialog('Hello World') %}
This is a simple dialog rendered by using a macro and
a call block.
{% endcall %}
```
--------------------------------
### Jinja Template Example with HTML
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
A basic Jinja template demonstrating HTML structure, a for loop for navigation, variable printing, and comments. It uses default Jinja delimiters: {% ... %} for statements, {{ ... }} for expressions, and {# ... #} for comments.
```html+jinja
My Webpage
{{ a_variable }}
{# a comment #}
```
--------------------------------
### Jinja FromImport Node Example
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/extensions.md
Represents a 'from ... import ...' statement in Jinja. It handles importing specific names from a template or module, including aliasing.
```python
jinja2.nodes.FromImport(template, names, with_context)
```
--------------------------------
### Jinja Continue Node Example
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/extensions.md
Represents the 'continue' statement within loops in Jinja templates. It allows skipping the rest of the current loop iteration and proceeding to the next.
```python
jinja2.nodes.Continue
```
--------------------------------
### Jinja Include with Context Options
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
Provides examples of using 'without context' and 'with context' with the 'include' tag to control context visibility for the included template. 'ignore missing' is also shown to prevent errors if a template doesn't exist.
```jinja
{% include "sidebar.html" without context %}
{% include "sidebar.html" ignore missing %}
{% include "sidebar.html" ignore missing with context %}
{% include "sidebar.html" ignore missing without context %}
```
--------------------------------
### Create Jinja Environment with PackageLoader (Python)
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/api.md
Demonstrates how to create a Jinja Environment configured to load templates from a Python package. It utilizes PackageLoader for locating templates and enables autoescaping for HTML. This is a common setup for web applications using Jinja.
```python
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader("yourapp"),
autoescape=select_autoescape()
)
```
--------------------------------
### Use a Custom Jinja Test in a Template
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/api.md
Shows the Jinja template syntax for utilizing a custom test that has been registered with the environment. This example uses the 'prime' test.
```jinja
{% if value is prime %}
{{ value }} is a prime number
{% else %}
{{ value }} is not a prime number
{% endif %}
```
--------------------------------
### Jinja For Loop Node Example
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/extensions.md
Represents a 'for' loop in Jinja. It iterates over an iterable, assigning each item to a target variable. It supports an optional 'else' block and recursive iteration.
```python
jinja2.nodes.For(target, iter, body, else_, test, recursive)
```
--------------------------------
### Create Jinja Overlay Environment
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/api.md
The overlay() method creates a new Jinja environment that inherits data from the current environment, excluding cache and overridden attributes. Extensions are automatically included and can be augmented. This is useful for creating isolated environments after initial setup.
```python
from jinja2 import Environment
# Assuming 'env' is an existing Jinja Environment object
# env = Environment(...)
# Example of creating an overlay environment with custom block delimiters
overlay_env = env.overlay(
block_start_string='<%',
block_end_string='%>',
variable_start_string='<<',
variable_end_string='>>'
)
```
--------------------------------
### Jinja Macro Import and Loop
Source: https://github.com/fahreddinozcan/jinja/blob/main/examples/basic/templates/broken.html
This snippet shows how to import a macro named 'may_break' from 'subbroken.html' and then iterate over a sequence 'seq', applying the macro to each item. It assumes 'seq' is a defined variable and 'subbroken.html' contains the 'may_break' macro definition.
```jinja
{% from 'subbroken.html' import may_break %}
{% for item in seq %}* {{ may_break(item) }}
{% endfor %}
```
--------------------------------
### MemcachedBytecodeCache Constructor and Interface (Python)
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/api.md
Demonstrates the constructor for Jinja2's MemcachedBytecodeCache, which utilizes a memcache client for storing compiled template bytecode. It outlines the required minimal interface for the memcache client, including 'set' and 'get' methods.
```python
class MemcachedBytecodeCache:
def __init__(self, client, prefix='jinja2/bytecode/', timeout=None, ignore_memcache_errors=True):
# ... implementation details ...
pass
class MinimalClientInterface:
def set(self, key, value):
# Stores the bytecode in the cache.
pass
def get(self, key):
# Returns the value for the cache key or None if not found.
pass
```
--------------------------------
### Jinja2 Macros: Reusable Template Functions
Source: https://context7.com/fahreddinozcan/jinja/llms.txt
Shows how to define and use Jinja2 macros for creating reusable template components, similar to functions. Includes examples of defining macros within a template and importing macros from other templates using DictLoader. Requires the Jinja2 library.
```python
from jinja2 import Environment
env = Environment()
template = env.from_string('''
{% macro input(name, value='', type='text', placeholder='') %}
{% endmacro %}
{% macro form_field(label, name, value='', type='text') %}
{{ input(name, value, type) }}
{% endmacro %}
''')
result = template.render(user={'email': 'user@example.com'})
print(result)
# Import macros from another template
from jinja2 import DictLoader
templates = {
'forms.html': '''
{% macro button(text, type='submit', class='btn') %}
{% endmacro %}
''',
'page.html': '''
{% from "forms.html" import button %}
{{ button('Save') }}
{{ button('Cancel', type='button', class='btn-secondary') }}
'''
}
env = Environment(loader=DictLoader(templates))
template = env.get_template('page.html')
print(template.render())
```
--------------------------------
### Import All Macros from a Jinja Template
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
This example shows how to import an entire Jinja template file ('forms.html') into a variable named 'forms'. This allows access to all macros and variables defined in the imported template using the variable name as a prefix.
```html+jinja
{% import 'forms.html' as forms %}
Username
{{ forms.input('username') }}
Password
{{ forms.input('password', type='password') }}
{{ forms.textarea('comment') }}
```
--------------------------------
### Jinja AST Node: Get Attribute/Item
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/extensions.md
Represents getting an attribute or item from an expression, prioritizing attributes. The target expression must be an ASCII-only bytestring.
```python
class jinja2.nodes.Getattr(node, attr, ctx):
# Get an attribute or item from an expression that is a ascii-only
# bytestring and prefer the attribute.
pass
```
--------------------------------
### Loop Controls: 'continue' and 'break' in Jinja
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
When the Loop Controls extension is enabled, 'break' and 'continue' can be used within loops. 'break' terminates the loop, while 'continue' skips the current iteration and proceeds to the next. 'loop.index' starts at 1, and 'loop.index0' starts at 0.
```html+jinja
{% for user in users %}
{%- if loop.index is even %}{% continue %}{% endif %}
...
{% endfor %}
```
```html+jinja
{% for user in users %}
{%- if loop.index >= 10 %}{% break %}{% endif %}
{%- endfor %}
```
--------------------------------
### Generate a range of numbers
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
The `range` global function generates a list of integers within a specified range. It can take one, two, or three arguments: `stop`, `start, stop`, or `start, stop, step`. This is useful for loops and creating sequences. The end point is exclusive.
```html+jinja
{% for user in users %}
{{ user.username }}
{% endfor %}
{% for number in range(10 - users|count) %}
...
{% endfor %}
```
--------------------------------
### Jinja Filters: title
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
Converts a string to title case, where words start with uppercase letters and the rest are lowercase.
```APIDOC
## jinja-filters.title
### Description
Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase.
### Method
Filter (used within Jinja templates)
### Endpoint
N/A (Jinja filter)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```jinja
{{ "hello world"|title }}
```
### Response
#### Success Response (200)
Titlecased string
#### Response Example
```
Hello World
```
```
--------------------------------
### Adding Jinja Extensions
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/extensions.md
Demonstrates how to add extensions to the Jinja environment, both during initialization and after creation.
```APIDOC
## Adding Extensions
Extensions are added to the Jinja environment at creation time or after creation.
### Adding during Environment Initialization
Pass a list of extension classes or import paths to the `extensions` parameter of the `Environment` constructor.
```python
from jinja2 import Environment
jinja_env = Environment(extensions=['jinja2.ext.i18n'])
```
### Adding after Environment Creation
Use the `add_extension()` method on an existing `Environment` object.
```python
jinja_env.add_extension('jinja2.ext.debug')
```
```
--------------------------------
### Jinja FilterBlock Node Example
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/extensions.md
Represents a filter section in Jinja templates. The content within the block is processed by the specified filter.
```python
jinja2.nodes.FilterBlock(body, filter)
```
--------------------------------
### Jinja Filters API
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
This section provides documentation for various Jinja built-in filters, detailing their purpose, parameters, and usage examples.
```APIDOC
## Jinja Filters Documentation
This document details the available built-in filters in Jinja, explaining how to use them for data manipulation and presentation within templates.
### Python Methods
You can also use any of the methods defined on a variable’s type. The value returned from the method invocation is used as the value of the expression.
Example using string methods:
```jinja
{{ page.title.capitalize() }}
```
Example using user-defined type methods:
```jinja
{{ f.bar(value) }}
```
Example using operator methods:
```jinja
{{ "Hello, %s!" % name }}
```
Preferring the `.format` method:
```jinja
{{ "Hello, {}!".format(name) }}
```
## List of Builtin Filters
| [`abs()`](#jinja-filters.abs) | [`forceescape()`](#jinja-filters.forceescape) | [`map()`](#jinja-filters.map) | [`select()`](#jinja-filters.select) | [`unique()`](#jinja-filters.unique) |
|-----------------------------------------------------|-------------------------------------------------|---------------------------------------------|---------------------------------------------|-------------------------------------------|
| [`attr()`](#jinja-filters.attr) | [`format()`](#jinja-filters.format) | [`max()`](#jinja-filters.max) | [`selectattr()`](#jinja-filters.selectattr) | [`upper()`](#jinja-filters.upper) |
| [`batch()`](#jinja-filters.batch) | [`groupby()`](#jinja-filters.groupby) | [`min()`](#jinja-filters.min) | [`slice()`](#jinja-filters.slice) | [`urlencode()`](#jinja-filters.urlencode) |
| [`capitalize()`](#jinja-filters.capitalize) | [`indent()`](#jinja-filters.indent) | [`pprint()`](#jinja-filters.pprint) | [`sort()`](#jinja-filters.sort) | [`urlize()`](#jinja-filters.urlize) |
| [`center()`](#jinja-filters.center) | [`int()`](#jinja-filters.int) | [`random()`](#jinja-filters.random) | [`string()`](#jinja-filters.string) | [`wordcount()`](#jinja-filters.wordcount) |
| [`default()`](#jinja-filters.default) | [`items()`](#jinja-filters.items) | [`reject()`](#jinja-filters.reject) | [`striptags()`](#jinja-filters.striptags) | [`wordwrap()`](#jinja-filters.wordwrap) |
| [`dictsort()`](#jinja-filters.dictsort) | [`join()`](#jinja-filters.join) | [`rejectattr()`](#jinja-filters.rejectattr) | [`sum()`](#jinja-filters.sum) | [`xmlattr()`](#jinja-filters.xmlattr) |
| [`escape()`](#jinja-filters.escape) | [`last()`](#jinja-filters.last) | [`replace()`](#jinja-filters.replace) | [`title()`](#jinja-filters.title) | |
| [`filesizeformat()`](#jinja-filters.filesizeformat) | [`length()`](#jinja-filters.length) | [`reverse()`](#jinja-filters.reverse) | [`tojson()`](#jinja-filters.tojson) | |
| [`first()`](#jinja-filters.first) | [`list()`](#jinja-filters.list) | [`round()`](#jinja-filters.round) | [`trim()`](#jinja-filters.trim) | |
| [`float()`](#jinja-filters.float) | [`lower()`](#jinja-filters.lower) | [`safe()`](#jinja-filters.safe) | [`truncate()`](#jinja-filters.truncate) | |
### jinja-filters.abs(x,)
Return the absolute value of the argument.
### jinja-filters.attr(obj: Any, name: [str](https://docs.python.org/3/library/stdtypes.html#str)) → [jinja2.runtime.Undefined](api.md#jinja2.Undefined) | [Any](https://docs.python.org/3/library/typing.html#typing.Any)
Get an attribute of an object. `foo|attr("bar")` works like `foo.bar`, but returns undefined instead of falling back to `foo["bar"]` if the attribute doesn’t exist.
See [Notes on subscriptions](#notes-on-subscriptions) for more details.
### jinja-filters.batch(value: 't.Iterable[V]', linecount: [int](https://docs.python.org/3/library/functions.html#int), fill_with: 'V | None' = None) → 't.Iterator[list[V]]'
A filter that batches items. It works pretty much like `slice` just the other way round. It returns a list of lists with the given number of items. If you provide a second parameter this is used to fill up missing items. See this example:
```html+jinja
{%- for row in items|batch(3, ' ') %}
{%- for column in row %}
{{ column }}
{%- endfor %}
{%- endfor %}
```
```
--------------------------------
### Jinja Filters: sum
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
Returns the sum of a sequence of numbers plus an optional start value. Can sum specific attributes of objects.
```APIDOC
## jinja-filters.sum
### Description
Returns the sum of a sequence of numbers plus the value of parameter ‘start’ (which defaults to 0). When the sequence is empty it returns start.
### Method
Filter (used within Jinja templates)
### Endpoint
N/A (Jinja filter)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```jinja
{{ items|sum(attribute='price') }}
```
### Response
#### Success Response (200)
Sum of the sequence
#### Response Example
N/A (Jinja filter output)
### Notes
- **iterable**: The sequence to sum.
- **attribute**: An optional attribute or key to sum from each element in the iterable.
- **start**: An optional starting value for the sum (defaults to 0).
```
--------------------------------
### Jinja Extends Node Example
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/extensions.md
Represents the 'extends' statement in Jinja, used for template inheritance. It specifies the parent template from which the current template inherits.
```python
jinja2.nodes.Extends(template)
```
--------------------------------
### Jinja Include with Template List
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
Shows how to provide a list of templates to the 'include' tag, which will try each template in order until one is found. This can be combined with 'ignore missing' to gracefully handle cases where none of the specified templates exist.
```jinja
{% include ['page_detailed.html', 'page.html'] %}
{% include ['special_sidebar.html', 'sidebar.html'] ignore missing %}
```
--------------------------------
### Load and Render Jinja Template (Python)
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/api.md
Shows how to load a specific template from a configured Jinja Environment and then render it with provided variables. This is a fundamental operation for generating dynamic content using Jinja.
```python
template = env.get_template("mytemplate.html")
print(template.render(the="variables", go="here"))
```
--------------------------------
### Jinja If Statement Node Example
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/extensions.md
Represents an 'if' statement in Jinja. It conditionally renders content based on a test expression, supporting 'elif' and 'else' blocks.
```python
jinja2.nodes.If(test, body, elif_, else_)
```
--------------------------------
### Jinja ScopedEvalContextModifier Node Example
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/extensions.md
Similar to EvalContextModifier, but the context modifications are only applied within the 'body' nodes and are reverted afterward. This ensures localized context changes.
```python
jinja2.nodes.ScopedEvalContextModifier(options, body)
```
--------------------------------
### Mako vs. Jinja: Template Structure
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/switching.md
Compares the syntax for template inheritance, defining blocks, and rendering lists between Mako and Jinja. Jinja uses `extends` and `block` keywords, while Mako uses `inherit` and `def`.
```mako
<%inherit file="layout.html" />
<%def name="title()">Page Title%def>
% for item in list:
${item}
% endfor
```
```jinja
<% extends "layout.html" %>
<% block title %>Page Title<% endblock %>
<% block body %>
% for item in list:
${item}
% endfor
<% endblock %>
```
--------------------------------
### Jinja EvalContextModifier Node Example
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/extensions.md
Modifies the evaluation context for a specific part of the template. Options are passed as a list of Keyword nodes, such as changing the 'autoescape' setting.
```python
EvalContextModifier(options=[Keyword('autoescape', Const(True))])
```
--------------------------------
### select_template
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/api.md
Tries loading multiple template names. Raises TemplatesNotFound if none of the names can be loaded.
```APIDOC
## select_template(names, parent=None, globals=None)
### Description
Like [`get_template()`](#jinja2.Environment.get_template), but tries loading multiple names. If none of the names can be loaded a [`TemplatesNotFound`](#jinja2.TemplatesNotFound) exception is raised.
### Method
Not applicable (this is a method within a class, not a standalone API endpoint).
### Endpoint
Not applicable.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
None
#### Response Example
None
### Parameters
- **names** (Iterable[str | Template]) - List of template names to try loading in order.
- **parent** (str | None) - The name of the parent template importing this template. [`join_path()`](#jinja2.Environment.join_path) can be used to implement name transformations with this.
- **globals** (MutableMapping[str, Any] | None) - Extend the environment [`globals`](#jinja2.Environment.globals) with these extra variables available for all renders of this template. If the template has already been loaded and cached, its globals are updated with any new items.
### Return type
Template
```
--------------------------------
### Jinja ExprStmt Node Example
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/extensions.md
Represents a statement that evaluates an expression but discards its result. This is useful for expressions that have side effects or are used for their return value in specific contexts.
```python
jinja2.nodes.ExprStmt(node)
```
--------------------------------
### Django vs. Jinja: Loops and Empty States
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/switching.md
Compares loop syntax and handling of empty lists. Django uses `forloop.counter` and an `empty` block, while Jinja uses `loop.index` and an `else` block.
```django
{% for item in items %}
{{ forloop.counter }}. {{ item }}
{% empty %}
No items!
{% endfor %}
```
```jinja
{% for item in items %}
{{ loop.index }}. {{ item }}
{% else %}
No items!
{% endfor %}
```
--------------------------------
### Jinja CallBlock Node Example
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/extensions.md
Represents a macro-like structure without a name, where a 'call' is invoked with the unnamed macro as a 'caller' argument. This node holds the body of the macro.
```python
jinja2.nodes.CallBlock(call, args, defaults, body)
```
--------------------------------
### Jinja2 AST Overview
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/extensions.md
An introduction to Jinja2's Abstract Syntax Tree (AST), which represents a template after parsing and is used by the compiler to generate Python code.
```APIDOC
### AST (Abstract Syntax Tree)
### Description
The AST is used to represent a template after parsing. It is composed of nodes that the compiler then converts into executable Python code objects. Extensions that provide custom statements can return nodes to execute custom Python code.
The AST may change between Jinja versions but will remain backwards compatible. For more information, refer to the repr of `jinja2.Environment.parse()`.
### Module
* `jinja2.nodes`
```
--------------------------------
### Jinja2 Template Rendering and Streaming in Python
Source: https://context7.com/fahreddinozcan/jinja/llms.txt
Illustrates how to create and render Jinja2 `Template` objects directly from strings, including the use of control structures like for loops. It also shows memory-efficient streaming for large templates and generating output piece by piece.
```python
from jinja2 import Template
# Direct template creation (simple use cases)
template = Template('Hello {{ name }}!')
result = template.render(name='World')
print(result)
# Output: Hello World!
# Template with control structures
template = Template('''
{% for item in items %}
{{ item.name }}: ${{ item.price }}
{% endfor %}
''')
result = template.render(items=[
{'name': 'Apple', 'price': 1.50},
{'name': 'Banana', 'price': 0.75}
])
print(result)
# Streaming large templates (memory efficient)
template = Template('{% for i in range(1000) %}{{ i }}\n{% endfor %}')
stream = template.stream()
stream.enable_buffering(size=5) # Buffer 5 items before yielding
# Write stream directly to file
stream.dump('output.txt')
# Generate output piece by piece
template = Template('{% for n in numbers %}{{ n }} {% endfor %}')
for chunk in template.generate(numbers=range(5)):
print(chunk, end='')
# Output: 0 1 2 3 4
```
--------------------------------
### Get Unique Items from Iterable with Jinja
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
Returns a list containing only the unique items from an iterable. It supports case-sensitive comparisons and filtering based on a specific object attribute.
```jinja
{{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}
-> ['foo', 'bar', 'foobar']
```
--------------------------------
### Initialize PackageLoader to load templates from a Python package
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/api.md
This Python code illustrates how to set up a `PackageLoader` to retrieve templates from a specific directory within a Python package. It requires the package's import name and the path to the template directory inside that package.
```python
from jinja2 import PackageLoader
loader = PackageLoader("project.ui", "pages")
```
--------------------------------
### Get Last Item of a Sequence (Jinja)
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
The `last` filter returns the last item of a sequence. It does not work with generators and may require explicit conversion to a list for such cases.
```jinja
{{ data | selectattr('name', '==', 'Jinja') | list | last }}
```
--------------------------------
### Initialize FileSystemLoader with a single path
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/api.md
This snippet demonstrates how to initialize a `FileSystemLoader` in Python, specifying a single directory to search for templates. The loader will look for template files within the 'templates' directory.
```python
from jinja2 import FileSystemLoader
loader = FileSystemLoader("templates")
```
--------------------------------
### jinja2.ModuleLoader
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/api.md
Loads templates from precompiled template bytecode.
```APIDOC
## jinja2.ModuleLoader
### Description
This loader loads templates from precompiled templates.
### Parameters
* **path** (str | os.PathLike[str] | Sequence[str | os.PathLike[str]]) - The path(s) to the directory containing the precompiled templates.
### Request Example
```python
loader = ModuleLoader('/path/to/compiled/templates')
```
```
--------------------------------
### Create a dictionary
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
The `dict` global function provides a convenient way to create dictionaries, serving as an alternative to dictionary literals. For example, `dict(foo='bar')` is equivalent to `{'foo': 'bar'}`.
```jinja
{{ dict(foo='bar') }}
```
--------------------------------
### Sum Iterable with Jinja
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
Calculates the sum of a sequence of numbers, optionally starting from a specified value. It can also sum specific attributes of objects or dictionary values within the iterable.
```jinja
Total: {{ items|sum(attribute='price') }}
```
--------------------------------
### Jinja Named Block End-Tags Example
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
Demonstrates using named end-tags in Jinja blocks for improved code readability. The name after 'endblock' must match the block's name.
```html+jinja
{% block sidebar %}
{% block inner_sidebar %}
...
{% endblock inner_sidebar %}
{% endblock sidebar %}
```
--------------------------------
### Django vs. Jinja: Cycle Usage
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/switching.md
Shows how to cycle through values within a loop. Django uses the `{% cycle %}` tag, while Jinja utilizes the `loop.cycle()` method or the global `cycle()` function.
```django
{% for user in users %}
{{ user }}
{% endfor %}
```
```jinja
{% for user in users %}
{{ user }}
{% endfor %}
```
--------------------------------
### Jinja2 Built-in and Custom Tests
Source: https://context7.com/fahreddinozcan/jinja/llms.txt
Demonstrates how to use Jinja2's built-in tests for type checking and comparisons, as well as how to define and use custom tests. Requires the Jinja2 library.
```python
from jinja2 import Environment
env = Environment()
# Built-in tests
template = env.from_string('''
{% if value is defined %}Defined{% endif %}
{% if value is none %}None{% endif %}
{% if value is string %}String{% endif %}
{% if value is number %}Number{% endif %}
{% if value is sequence %}Sequence{% endif %}
{% if value is mapping %}Mapping{% endif %}
{% if value is iterable %}Iterable{% endif %}
{% if value is callable %}Callable{% endif %}
{% if num is odd %}Odd{% endif %}
{% if num is even %}Even{% endif %}
{% if num is divisibleby(3) %}Divisible by 3{% endif %}
{% if value is sameas(other) %}Same object{% endif %}
{% if text is lower %}Lowercase{% endif %}
{% if text is upper %}Uppercase{% endif %}
{% if item is in(collection) %}In collection{% endif %}
''')
# Custom test
def is_valid_email(value):
return '@' in value and '.' in value.split('@')[1]
env.tests['valid_email'] = is_valid_email
template = env.from_string('{% if email is valid_email %}Valid{% else %}Invalid{% endif %}')
print(template.render(email='user@example.com'))
# Output: Valid
```
--------------------------------
### Environment.preprocess
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/api.md
Preprocesses the source code with all extensions. Automatically called for parsing and compiling methods.
```APIDOC
## Environment.preprocess
### Description
Preprocesses the source with all extensions. This is automatically called for all parsing and compiling methods but not for `lex()`.
### Method
`preprocess`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
* **source** (str) - The source code to preprocess.
* **name** (str | None) - Optional name for the source.
* **filename** (str | None) - Optional filename for the source.
### Request Example
```python
env.preprocess('{{ variable }}')
```
### Response
#### Success Response (200)
* **str** - The preprocessed source code.
#### Response Example
```
'{{ variable }}'
```
```
--------------------------------
### Standard Gettext Calls with Format Filter in Jinja
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/extensions.md
Illustrates the traditional way of using gettext calls in Jinja, where string formatting is handled as a separate step using the `|format` filter. This approach can be more verbose, especially for ngettext calls.
```jinja
{{ gettext("Hello, World!") }}
{{ gettext("Hello, %(name)s!")|format(name=name) }}
{{ ngettext(
"%(num)d apple", "% (num)d apples", apples|count
)|format(num=apples|count) }}
{{ pgettext("greeting", "Hello, World!") }}
{{ npgettext(
"fruit", "% (num)d apple", "% (num)d apples", apples|count
)|format(num=apples|count) }}
```
--------------------------------
### Jinja Macro with Call Block and Arguments
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
Illustrates using the 'call' block with arguments to pass data back to the macro, effectively replacing traditional loops. This is useful for iterating over data and rendering custom HTML for each item.
```html+jinja
{% macro dump_users(users) -%}
{% endcall %}
```
--------------------------------
### Intercept Binary Operators in Jinja2 Sandbox (Python)
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/sandbox.md
This example demonstrates how to intercept binary operators within a Jinja2 SandboxedEnvironment. By overriding intercepted_binops and call_binop, you can control or disable specific operators like the power operator (**).
```python
from jinja2.sandbox import SandboxedEnvironment
class MyEnvironment(SandboxedEnvironment):
intercepted_binops = frozenset(["**"])
def call_binop(self, context, operator, left, right):
if operator == "**":
return self.undefined("The power (**) operator is unavailable.")
return super().call_binop(self, context, operator, left, right)
```
--------------------------------
### Jinja Template Objects for Extends
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
Demonstrates using Python template objects directly with Jinja's 'extends' tag, allowing dynamic template loading based on application logic.
```python
if debug_mode:
layout = env.get_template("debug_layout.html")
else:
layout = env.get_template("layout.html")
user_detail = env.get_template("user/detail.html")
return user_detail.render(layout=layout)
```
```jinja
{% extends layout %}
```
--------------------------------
### Filter Items in Jinja Loop
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/templates.md
Shows how to filter items directly within a 'for' loop using an 'if' condition. This example skips users marked as 'hidden' and ensures the 'loop' variable counts correctly.
```html+jinja
{% for user in users if not user.hidden %}
{{ user.username|e }}
{% endfor %}
```
--------------------------------
### Jinja2 SandboxedEnvironment for Secure Template Execution
Source: https://context7.com/fahreddinozcan/jinja/llms.txt
Demonstrates the use of Jinja2's SandboxedEnvironment and ImmutableSandboxedEnvironment to safely render untrusted templates by restricting access to potentially dangerous attributes and operations. Requires the Jinja2 library.
```python
from jinja2.sandbox import SandboxedEnvironment, ImmutableSandboxedEnvironment
from jinja2.sandbox import is_internal_attribute, modifies_known_mutable
# Basic sandboxed environment
env = SandboxedEnvironment()
# Safe template rendering
template = env.from_string('Hello {{ name }}!')
print(template.render(name='World'))
# Output: Hello World!
# Dangerous access is blocked
template = env.from_string('{{ func.__code__ }}')
try:
template.render(func=lambda: None)
except Exception as e:
print(f"Blocked: {e}")
# Output: Blocked: access to attribute '__code__' of 'function' object is unsafe.
# Immutable sandbox prevents modifying collections
env = ImmutableSandboxedEnvironment()
template = env.from_string('{% do items.append("new") %}')
try:
template.render(items=[1, 2, 3])
except Exception as e:
print(f"Blocked: {e}")
```
--------------------------------
### Configure Jinja Environment Policies
Source: https://github.com/fahreddinozcan/jinja/blob/main/docs/api.md
This snippet demonstrates how to configure Jinja environment policies, which can influence the behavior of filters and other template constructs. Policies are set on the `Environment` object's `policies` attribute. Example shown for `urlize.rel`.
```python
env.policies['urlize.rel'] = 'nofollow noopener'
```