What is the Django Template Language (DTL)?
The Django Template Language is a text-based language designed to strike a balance between power and ease of use. It allows developers to define the structure of the UI while leaving 'holes' for data provided by the View. Because it is not pure Python, it is safe to allow designers to edit templates without risking the execution of malicious backend code.
- Rendering a Template
In Django, a View fetches data (the context) and passes it to a template. By default, Django looks for a 'templates' folder inside each installed app.
- Template Syntax
DTL uses four main types of constructs to handle data and logic:
- Variables
{{ variable }}: Outputs a value from the context. If the value is an object, you can use dot notation (e.g.,{{ user.name }}). - Tags
{% tag %}: Controls the logic of the template (loops, ifs, and inheritance). - Filters
{{ var|filter }}: Modifies variables for display (e.g.,{{ name|lower }}). - Comments
{# comment #}: Internal notes that are not rendered in the final HTML.
- Template Inheritance
Inheritance is the most powerful part of Django's template engine. You define a 'base' skeleton and use blocks that child templates can override.
Common Template Tags & Filters
| Type | Syntax | Description |
|---|---|---|
| Loop | {% for item in list %} | Iterates over a sequence |
| Condition | {% if user.is_authenticated %} | Conditional rendering |
| URL | {% url 'view-name' %} | Reverse URL resolution (best practice) |
| Static | {% static 'css/style.css' %} | Links to static assets |
| Filter | {{ date|date:'Y-m-d' }} | Formats date objects |
| CSRF | {% csrf_token %} | Protects forms from cross-site request forgery |