Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 77 ยท Templates

Django Templates

Learn the Django template language. Render variables, apply filters, use if and for tags, write comments, understand autoescaping, and run templates with Engine and Context.

A view decides what to show. A template decides how it looks. Django's template language is deliberately small: plain text (usually HTML) sprinkled with variables, filters and tags. It is not Python, and that is on purpose. Keeping real logic out of templates lets designers edit them safely and keeps your business rules in views and models, where you can test them.

In this lesson you will learn the four building blocks of the syntax, render templates directly with Django's Engine (no project needed), loop and branch, and see how automatic escaping protects you from cross-site scripting. Inheritance and includes come next in Template Inheritance and Includes.

The four building blocks

Syntax Name Example
{{ ... }} Variable {{ user.name }}
{{ value|filter }} Filter (transforms a value) {{ title|upper }}
{% ... %} Tag (logic and control flow) {% if admin %}...{% endif %}
{# ... #} Comment (never rendered) {# TODO #}

A template is rendered against a context: a dictionary of names the template may use. The view builds the context and passes it to render(); here we will do the same by hand.

flowchart LR
    T["Template text<br/>with {{ }} and {% %}"] --> R["render(context)"]
    C["Context<br/>name to value"] --> R
    R --> O["Final string (HTML)"]

A template plus a context produces output. Neither one is useful alone.

Variables and filters

{{ name }} looks the name up in the context and prints it. Dots do lookups with a fixed order of attempts: first a dictionary key, then an attribute, then a list index. So {{ book.author.name }}, {{ book.tags.0 }} and {{ book.title }} all work whether book is a dictionary, an object or a mix. If something is a callable (a method or function), Django calls it without arguments. If a lookup fails, the result is an empty string instead of an error. That forgiveness is a feature for designers and a trap for typos.

Filters follow a pipe and can take one argument after a colon: {{ price|floatformat:2 }}. They chain left to right.

Python Variables and filters with Engine.from_string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Engine() is the template engine on its own; in a project you normally configure it through the TEMPLATES setting and call render(request, "page.html", context) from a view. The behavior is identical.

Useful built-in filters:

Filter Does
default:"x" Fallback for empty or false values
length Size of a list or string
lower, upper, title Case changes
truncatechars:20, truncatewords:5 Shorten text with an ellipsis
date:"Y-m-d" Format a date or datetime
floatformat:2 Round a number to decimals
join:", " Join a list
pluralize Add "s" depending on a number
slice:":3" Slice a list or string
linebreaksbr, urlize Turn text into HTML breaks or links

You can write your own filters; see Custom Template Tags and Filters.

Logic with tags

Tags look like {% name ... %}. Block tags need a matching end tag.

  • {% if %}, {% elif %}, {% else %}, {% endif %} branch on conditions. You may use and, or, not, in, ==, !=, <, >. There is no way to write a function call or assignment.
  • {% for x in items %} ... {% empty %} ... {% endfor %} loops; the {% empty %} part runs when the list is empty.
  • Inside a loop you get forloop.counter (from 1), forloop.counter0, forloop.first, forloop.last and forloop.parentloop.
  • {% with first=items.0 %} binds a short name to an expensive or long expression inside the block.
  • {% url 'name' arg %} builds a URL from a named pattern, {% csrf_token %} adds the CSRF field to forms, and {% load %} brings in extra tag libraries.
Python if, for, empty and with

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice how the empty cart reaches the {% empty %} branch, how forloop.last marks the final row, and how {{ first.name|default:"-" }} survives a missing first item. The stray blank lines in the raw output come from the tag lines themselves, which is why the example filters them out with show(). Django has no whitespace-control syntax like some other engines, and for HTML it rarely matters.

A word of caution about dots. Because dictionary lookup comes first, {{ d.items }} on a dictionary with a key called items returns that value, not the items() method. Avoid dictionary keys named items, keys or values if a template needs the method.

Escaping and safety

Django escapes every variable by default: < becomes &lt;, & becomes &amp;, quotes become entities. This is the main defense against cross-site scripting (XSS), because user text cannot inject tags. You turn it off only for strings you built yourself and know to be safe.

Python Autoescaping, safe and autoescape off

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first output escapes the markup, the second and third print it raw. Use |safe and {% autoescape off %} only on content you control, never on anything a visitor typed. The same section shows the dictionary quirk: d.items found the key "items", while d.keys fell through to the method. For deeper coverage of escaping, mark_safe and the other defenses, read Security in Django.

Using Jinja2 instead of the Django template language

The template engine is replaceable. Django ships two backends: DjangoTemplates (the language you have been using) and Jinja2. Jinja2 is a separate library (pip install jinja2) with a similar look but a more Python-like syntax: you can call methods with arguments (user.name.upper()), use {% set %}, write expressions such as 10 // 3, and apply filters with arguments in parentheses (items|join(", ")). Some teams choose it for speed or for sharing templates with Flask code. Both engines can run side by side, each with its own NAME.

Python Two template engines in one project

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The shared template renders identically in both engines, and both escape the <Ada> input. The Jinja-only syntax then works in Jinja2 and fails in the Django language, because Django templates deliberately cannot call a method with arguments.

With the Jinja2 backend the Django-specific tags ({% url %}, {% csrf_token %}, {% static %}) are not available unless you add an environment function that registers them as globals; the admin and other contrib apps keep using DjangoTemplates. For most projects the built-in language is the right default, and the Jinja2 option matters mainly when you migrate an existing Jinja code base.

Templates in a project

In a real project you will rarely call Engine yourself. A TEMPLATES setting lists backends and directories; a view calls render(request, "blog/post.html", {"post": post}); and with request available, context processors add names such as request, user and messages to every template. Put project-wide templates in a templates/ folder at the project root and app templates in <app>/templates/<app>/. The second <app>/ level prevents two apps from clobbering each other's index.html.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which syntax prints the value of title with its first letters capitalized?

    Variables use double braces, and filters follow a pipe. Method calls with arguments and parentheses are not allowed in templates.
  2. 2. A variable name is missing from the context. What does {{ missing }} render by default?

    Failed lookups render as an empty string. That is forgiving, so check typos carefully (the string_if_invalid option can reveal them).
  3. 3. What does the {% empty %} tag inside {% for %} do?

    The {% empty %} branch of a for loop is rendered only when the sequence is empty.
  4. 4. A user submits <script>alert(1)</script> as a comment. What does {{ comment }} output?

    Autoescaping converts the angle brackets to entities, so the browser displays the text instead of executing it.
  5. 5. What is a template context?

    The context maps names to values. The template language reads variables only from it.

Summary

  • Templates mix text with variables {{ }}, filters |, tags {% %} and comments {# #}.
  • Dot lookup tries dictionary key, attribute, then list index; callables are called; failures render empty.
  • Filters transform values and can chain: {{ x|default:"-"|upper }}.
  • {% if %}, {% for %} (with {% empty %} and forloop) and {% with %} cover most logic; keep heavy logic in views and models.
  • Variables are autoescaped, which blocks XSS; use |safe and autoescape off only for trusted HTML.
  • Engine().from_string(...).render(Context({...})) renders templates without a project.

Next, stop repeating your page layout in Template Inheritance and Includes.