{% tag %} syntax.
Template Inheritance
{% block %}
{% block %}
Define a block that child templates can override.Syntax:Example:Notes:
- Block names must be unique within a template
- Use
{{ block.super }}to include parent content - Can be nested
{% extends %}
{% extends %}
Declare that this template extends a parent template.Syntax:Example:Notes:
- Must be the first tag in the template
- Can use a variable for dynamic parent selection
- Only content inside
{% block %}tags is rendered
{% include %}
{% include %}
Load and render another template with the current context.Syntax:Examples:Notes:
- Included template has access to parent context by default
- Use
withto add extra variables - Use
onlyto isolate context
Control Flow
{% if %}
{% if %}
Evaluate a condition and render content conditionally.Syntax:Operators:Notes:
==,!=,<,>,<=,>=and,or,notin,not in
- Operators must have spaces:
{% if 1 > 2 %}not{% if 1>2 %} - Operator precedence follows Python
- Can use filters in conditions
{% for %}
{% for %}
Loop over items in a sequence.Syntax:Loop Variables:Notes:
forloop.counter- Current iteration (1-indexed)forloop.counter0- Current iteration (0-indexed)forloop.revcounter- Iterations from end (1-indexed)forloop.revcounter0- Iterations from end (0-indexed)forloop.first- True on first iterationforloop.last- True on last iterationforloop.parentloop- Parent loop in nested loops
- Use
reversedto iterate in reverse - Can unpack tuples/lists
{% empty %}is shorthand for checking if list is empty
{% ifchanged %}
{% ifchanged %}
Check if a value has changed from the last iteration.Syntax:Examples:Notes:
- Without arguments, compares rendered output
- With arguments, compares specified variables
- State is bound to the nearest for loop
Variable Assignment
{% with %}
{% with %}
Cache complex variables under simpler names.Syntax:Examples:Legacy syntax (still supported):
URL Handling
{% url %}
{% url %}
Return an absolute URL path matching a given view.Syntax:Examples:Notes:
- Returns empty string if reverse match fails (when using
as) - Otherwise raises
NoReverseMatch - Arguments can be variables or literals
- Don’t mix positional and keyword arguments
{% querystring %}
{% querystring %}
Build a query string by modifying the current request’s GET parameters.Syntax:Examples:Notes:
- Returns query string with
?prefix - Uses
request.GETby default - Setting value to
Noneremoves the parameter - Preserves other existing parameters
Template Loading
{% load %}
{% load %}
Load custom template tag library.Syntax:Examples:Built-in libraries:
static- Static file handlingi18n- Internationalizationhumanize- Human-friendly datatz- Timezone support
Utilities
{% csrf_token %}
{% csrf_token %}
Output a CSRF token for forms.Syntax:Example:Output:Notes:
- Required for POST forms
- Context must include CSRF token (use RequestContext)
{% cycle %}
{% cycle %}
Cycle through values each time the tag is encountered.Syntax:Examples:
{% resetcycle %}
{% resetcycle %}
Reset a cycle tag to its first value.Syntax:Example:
{% firstof %}
{% firstof %}
Output the first variable that is not False.Syntax:Examples:Equivalent to:
{% now %}
{% now %}
Display the current date and/or time.Syntax:Format: Uses PHP date() format (see https://php.net/date)Examples:
{% regroup %}
{% regroup %}
Regroup a list of objects by a common attribute.Syntax:Example:Result structure:
group.grouper- The value grouped bygroup.list- List of items with that value
- Input list must be sorted by the grouping attribute
- Use
dictsortfilter to sort first:{% regroup data|dictsort:"attr" by attr as grouped %}
{% widthratio %}
{% widthratio %}
Calculate a ratio for creating bar charts and similar visualizations.Syntax:Formula:
(current_value / max_value) * max_widthExamples:Text Processing
{% filter %}
{% filter %}
Filter the contents of a block through one or more filters.Syntax:Examples:Notes:
- Cannot use
escapeorsafefilters (use{% autoescape %}instead) - Can chain multiple filters
{% autoescape %}
{% autoescape %}
Control auto-escaping for a block.Syntax:Examples:Notes:
- Auto-escaping is on by default
- Use
{{ var|safe }}to mark individual variables as safe
{% verbatim %}
{% verbatim %}
Prevent the template engine from rendering a block.Syntax:Examples:Use cases:
- Embedding other template syntaxes (Mustache, Handlebars)
- Showing Django template code examples
{% spaceless %}
{% spaceless %}
Remove whitespace between HTML tags.Syntax:Example:Output:Notes:
- Only removes space between tags, not inside tags
- Doesn’t remove space between tags and text
{% lorem %}
{% lorem %}
Generate random Lorem Ipsum text.Syntax:Parameters:
count- Number of paragraphs/words (default: 1)method-w(words),p(HTML paragraphs),b(plain blocks, default)random- Use random text instead of common Lorem Ipsum
Debugging
{% debug %}
{% debug %}
Output debugging information about the current context and available modules.Syntax:Example:Notes:
- Only works when
DEBUG = True - Shows all context variables and their values
- Shows loaded Python modules
{% comment %}
{% comment %}
Ignore everything between opening and closing tags.Syntax:Example:Alternative:
{% templatetag %}
{% templatetag %}
Output template tag characters literally.Syntax:Tag types:
openblock-{%closeblock-%}openvariable-{{closevariable-}}openbrace-{closebrace-}opencomment-{#closecomment-#}
Partials (New in Django 5.0+)
{% partialdef %}
{% partialdef %}
Define a reusable partial within a template.Syntax:Examples:Notes:
- Use
inlineto render the partial at definition point - Partial names must be unique per template
{% partial %}
{% partial %}
Render a previously defined partial.Syntax:Example:Accessing from templates: