Template Engine Basics
Template Engine Basics
Django's built-in Django Template Language (DTL) is designed to balance power with ease of use. It bridges backend Python view logic and frontend HTML presentation. DTL enforces a strict separation of concerns: templates control presentation, while business logic remains in Python views and models.
1. DTL Syntax Building Blocks
Django templates use four primary syntactic constructs:
- 1Variables (
{{ variable }}): Evaluates a variable from the context and outputs its string value. - 2Tags (
{% tag %}): Executes template logic, such as loops, conditional blocks, template inheritance, and URL resolution. - 3Filters (
{{ value|filter }}): Modifies variables prior to display (e.g.{{ title|title }},{{ created_at|date:"M d, Y" }}). - 4Comments (
{# comment #}): Comments omitted from the final HTML output.
2. Template Variables & Dot Notation
DTL uses dot notation (.) to traverse objects, dictionaries, and methods:
Lookup Priority Order:
When evaluating foo.bar, Django tries in order:
- 1Dictionary lookup (
foo['bar']) - 2Attribute lookup (
foo.bar) - 3Method call (
foo.bar()) - Note: methods that require arguments cannot be called in DTL! - 4List-index lookup (
foo[bar])
3. Core Template Tags
Conditional Blocks (if, elif, else)
Looping with for and empty
The {% empty %} block executes automatically if the list is empty or undefined, eliminating boilerplate {% if articles %} wrapping!
4. Useful Built-in Filters
|lower/|upper/|title: String case formatting.|truncatewords:30: Truncates text after 30 words with....|date:"F j, Y, g:i a": Formats dates (e.g. "September 15, 2026, 4:45 am").|default:"N/A": Fallback if variable is false, empty, or None.|length: Returns the count of items in an array or string.
5. Reverse URL Resolution with {% url %}
Never hardcode relative URLs (/articles/5/) in HTML templates. Use the {% url %} tag to dynamically generate URLs from view names:
If you ever change your URL routing structure in urls.py, all template links update automatically without broken links!
Practice Quiz
Template Inheritance
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Django Forms & Validation | Template Inheritance |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.