Templates¶
Being a web framework, Django needs a convenient way to generate HTML dynamically. The most common approach relies on templates. A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted. For a hands-on example of creating HTML pages with templates, see Tutorial 3 .
A Django project can be configured with one or several template engines (or even zero if you don’t use templates). Django ships built-in backends for its own template system, creatively called the Django template language (DTL), and for the popular alternative Jinja2. Backends for other template languages may be available from third-parties. You can also write your own custom backend, see Custom template backend
Django defines a standard API for loading and rendering templates regardless of the backend. Loading consists of finding the template for a given identifier and preprocessing it, usually compiling it to an in-memory representation. Rendering means interpolating the template with context data and returning the resulting string.
The Django template language is Django’s own template system. Until Django 1.8 it was the only built-in option available. It’s a good template library even though it’s fairly opinionated and sports a few idiosyncrasies. If you don’t have a pressing reason to choose another backend, you should use the DTL, especially if you’re writing a pluggable application and you intend to distribute templates. Django’s contrib apps that include templates, like django.contrib.admin , use the DTL.
For historical reasons, both the generic support for template engines and the implementation of the Django template language live in the django.template namespace.
The template system isn’t safe against untrusted template authors. For example, a site shouldn’t allow its users to provide their own templates, since template authors can do things like perform XSS attacks and access properties of template variables that may contain sensitive information.
The Django template language¶
Syntax¶
This is an overview of the Django template language’s syntax. For details see the language syntax reference .
A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags.
A template is rendered with a context. Rendering replaces variables with their values, which are looked up in the context, and executes tags. Everything else is output as is.
The syntax of the Django template language involves four constructs.
Variables¶
A variable outputs a value from the context, which is a dict-like object mapping keys to values.
Variables are surrounded by > like this:
My first name is first_name >>. My last name is last_name >>.
With a context of , this template renders to:
My first name is John. My last name is Doe.
Dictionary lookup, attribute lookup and list-index lookups are implemented with a dot notation:
my_dict.key >> my_object.attribute >> my_list.0 >>
If a variable resolves to a callable, the template system will call it with no arguments and use its result instead of the callable.
Tags¶
Tags provide arbitrary logic in the rendering process.
This definition is deliberately vague. For example, a tag can output content, serve as a control structure e.g. an “if” statement or a “for” loop, grab content from a database, or even enable access to other template tags.
Tags are surrounded by like this:
Most tags accept arguments:
Some tags require beginning and ending tags:
if user.is_authenticated %>Hello, user.username >>. endif %>
Filters¶
Filters transform the values of variables and tag arguments.
The Web Framework For Perfectionists With Deadlines
Some filters take an argument:
How to create custom template tags and filters¶
Django’s template language comes with a wide variety of built-in tags and filters designed to address the presentation logic needs of your application. Nevertheless, you may find yourself needing functionality that is not covered by the core set of template primitives. You can extend the template engine by defining custom tags and filters using Python, and then make them available to your templates using the tag.
Code layout¶
The most common place to specify custom template tags and filters is inside a Django app. If they relate to an existing app, it makes sense to bundle them there; otherwise, they can be added to a new app. When a Django app is added to INSTALLED_APPS , any tags it defines in the conventional location described below are automatically made available to load within templates.
The app should contain a templatetags directory, at the same level as models.py , views.py , etc. If this doesn’t already exist, create it — don’t forget the __init__.py file to ensure the directory is treated as a Python package.
Development server won’t automatically restart
After adding the templatetags module, you will need to restart your server before you can use the tags or filters in templates.
Your custom tags and filters will live in a module inside the templatetags directory. The name of the module file is the name you’ll use to load the tags later, so be careful to pick a name that won’t clash with custom tags and filters in another app.
For example, if your custom tags/filters are in a file called poll_extras.py , your app layout might look like this:
polls/ __init__.py models.py templatetags/ __init__.py poll_extras.py views.py
And in your template you would use the following:
There’s no limit on how many modules you put in the templatetags package. Just keep in mind that a statement will load tags/filters for the given Python module name, not the name of the app.
To be a valid tag library, the module must contain a module-level variable named register that is a template.Library instance, in which all the tags and filters are registered. So, near the top of your module, put the following:
from django import template register = template.Library()
Alternatively, template tag modules can be registered through the ‘libraries’ argument to DjangoTemplates . This is useful if you want to use a different label from the template tag module name when loading template tags. It also enables you to register tags without installing an application.
For a ton of examples, read the source code for Django’s default filters and tags. They’re in django/template/defaultfilters.py and django/template/defaulttags.py, respectively.
For more information on the load tag, read its documentation.
Writing custom template filters¶
Custom filters are Python functions that take one or two arguments:
- The value of the variable (input) – not necessarily a string.
- The value of the argument – this can have a default value, or be left out altogether.
For example, in the filter > , the filter foo would be passed the variable var and the argument «bar» .
Since the template language doesn’t provide exception handling, any exception raised from a template filter will be exposed as a server error. Thus, filter functions should avoid raising exceptions if there is a reasonable fallback value to return. In case of input that represents a clear bug in a template, raising an exception may still be better than silent failure which hides the bug.
Here’s an example filter definition:
def cut(value, arg): """Removes all values of arg from the given string""" return value.replace(arg, "")
And here’s an example of how that filter would be used:
Most filters don’t take arguments. In this case, leave the argument out of your function:
def lower(value): # Only one argument. """Converts a string into all lowercase""" return value.lower()
Registering custom filters¶
Once you’ve written your filter definition, you need to register it with your Library instance, to make it available to Django’s template language:
register.filter("cut", cut) register.filter("lower", lower)
The Library.filter() method takes two arguments:
- The name of the filter – a string.
- The compilation function – a Python function (not the name of the function as a string).
You can use register.filter() as a decorator instead:
@register.filter(name="cut") def cut(value, arg): return value.replace(arg, "") @register.filter def lower(value): return value.lower()
If you leave off the name argument, as in the second example above, Django will use the function’s name as the filter name.
Finally, register.filter() also accepts three keyword arguments, is_safe , needs_autoescape , and expects_localtime . These arguments are described in filters and auto-escaping and filters and time zones below.
Template filters that expect strings¶
If you’re writing a template filter that only expects a string as the first argument, you should use the decorator stringfilter . This will convert an object to its string value before being passed to your function:
from django import template from django.template.defaultfilters import stringfilter register = template.Library() @register.filter @stringfilter def lower(value): return value.lower()
This way, you’ll be able to pass, say, an integer to this filter, and it won’t cause an AttributeError (because integers don’t have lower() methods).
Filters and auto-escaping¶
When writing a custom filter, give some thought to how the filter will interact with Django’s auto-escaping behavior. Note that two types of strings can be passed around inside the template code:
- Raw strings are the native Python strings. On output, they’re escaped if auto-escaping is in effect and presented unchanged, otherwise.
- Safe strings are strings that have been marked safe from further escaping at output time. Any necessary escaping has already been done. They’re commonly used for output that contains raw HTML that is intended to be interpreted as-is on the client side. Internally, these strings are of type SafeString . You can test for them using code like:
from django.utils.safestring import SafeString if isinstance(value, SafeString): # Do something with the "safe" string. .
Template filter code falls into one of two situations:
- Your filter does not introduce any HTML-unsafe characters ( < , >, ‘ , » or & ) into the result that were not already present. In this case, you can let Django take care of all the auto-escaping handling for you. All you need to do is set the is_safe flag to True when you register your filter function, like so:
@register.filter(is_safe=True) def myfilter(value): return value
This flag tells Django that if a “safe” string is passed into your filter, the result will still be “safe” and if a non-safe string is passed in, Django will automatically escape it, if necessary. You can think of this as meaning “this filter is safe – it doesn’t introduce any possibility of unsafe HTML.” The reason is_safe is necessary is because there are plenty of normal string operations that will turn a SafeData object back into a normal str object and, rather than try to catch them all, which would be very difficult, Django repairs the damage after the filter has completed. For example, suppose you have a filter that adds the string xx to the end of any input. Since this introduces no dangerous HTML characters to the result (aside from any that were already present), you should mark your filter with is_safe :
@register.filter(is_safe=True) def add_xx(value): return "%sxx" % value
from django import template from django.utils.html import conditional_escape from django.utils.safestring import mark_safe register = template.Library() @register.filter(needs_autoescape=True) def initial_letter_filter(text, autoescape=True): first, other = text[0], text[1:] if autoescape: esc = conditional_escape else: esc = lambda x: x result = " %s %s" % (esc(first), esc(other)) return mark_safe(result)
Avoiding XSS vulnerabilities when reusing built-in filters
Django’s built-in filters have autoescape=True by default in order to get the proper autoescaping behavior and avoid a cross-site script vulnerability.
In older versions of Django, be careful when reusing Django’s built-in filters as autoescape defaults to None . You’ll need to pass autoescape=True to get autoescaping.
For example, if you wanted to write a custom filter called urlize_and_linebreaks that combined the urlize and linebreaksbr filters, the filter would look like:
from django.template.defaultfilters import linebreaksbr, urlize @register.filter(needs_autoescape=True) def urlize_and_linebreaks(text, autoescape=True): return linebreaksbr(urlize(text, autoescape=autoescape), autoescape=autoescape)
comment|urlize_and_linebreaks >>