Django template syntax¶
- template is a text file. It can generate any text-based format (HTML, XML, CSV, etc.).
- template contains variables , which get replaced with values when the template is evaluated
- template tags control the logic of the template.
template.html
{% extends "base_generic.html" %}
{% block title %}{{ section.title }}{% endblock %}
{% block content %}
<h1>{{ section.title }}</h1>
{% for story in story_list %}
<h2>
<a href="{{ story.get_absolute_url }}">
{{ story.headline|upper }}
</a>
</h2>
<p>{{ story.tease|truncatewords:"100" }}</p>
{% endfor %}
{% endblock %}
template variables¶
- Variables look like this:
{{ variable }}
. - When the template engine encounters a variable, it evaluates that variable and replaces it with the result.
- Use a dot (.) to access attributes of a variable.
template.html
{{ section.title }}
{{ foo }}
template filters¶
- we can modify variables for display by using filters .
- filters look like this:
{{ name|lower }}
wherename
is a variable andlower
is a filter. lower
converts the value of name to lowercase
Filter | Description | Example Usage |
---|---|---|
date | Formats a date according to a given format string. | {{ my_date|date:"F j, Y" }} |
time | Formats a time according to a given format string. | {{ my_time|time:"H" }} |
default | Provides a default value if the variable is None or empty. | {{ my_var|default:"N/A" }} |
default_if_none | Provides a default value only if the variable is None. | {{ my_var|default_if_none:"N/A" }} |
length | Returns the length of the value. | {{ my_list|length }} |
lower | Converts a string to lowercase. | {{ my_string|lower }} |
upper | Converts a string to uppercase. | {{ my_string|upper }} |
title | Converts a string to title case. | {{ my_string|title }} |
truncatewords | Truncates a string to the specified number of words. | {{ my_string|truncatewords:3 }} |
truncatechars | Truncates a string to the specified number of characters. | {{ my_string|truncatechars:10 }} |
default | Returns a default value if the variable is None. | {{ name|default:"Guest" }} |
length | Returns the length of the value. | {{ items|length }} |
join | Joins a list with a string. | {{ list|join:", " }} |
yesno | Converts boolean values to strings. | {{ my_bool|yesno:"yes,no,maybe" }} |
safe | Marks a string as safe for HTML output. | {{ my_html|safe }} |
escape | Escapes a string’s HTML. | {{ my_string|escape }} |
linebreaks | Converts newlines into <p> and <br> tags. | {{ my_text|linebreaks }} |
urlize | Converts URLs in plain text into clickable links. | {{ my_text|urlize }} |
pluralize | Adds an 's' to a word if the value is not 1. | {{ count|pluralize }} |
slice | Returns a slice of the value. | {{ my_list|slice:":2" }} |
add | Adds a number to the value. | {{ num|add:5 }} |
divisibleby | Returns True if the value is divisible by the argument. | {{ num|divisibleby:3 }} |
filesizeformat | Formats a number of bytes as a human-readable file size. | {{ size|filesizeformat }} |
first | Returns the first item in a list. | {{ my_list|first }} |
last | Returns the last item in a list. | {{ my_list|last }} |
random | Returns a random item from a list. | {{ my_list|random }} |
striptags | Strips HTML tags from a string. | {{ my_html|striptags }} |
template tags¶
- Tags look like this:
{% tag %}
. - Some tags require beginning and ending tags (i.e.
{% tag %} ... tag contents ... {% endtag %}
).
Tag | Description | Example Usage |
---|---|---|
{% for %} | Loop over a sequence. | <ul> {% for item in items %} <li>{{ item }}</li> {% endfor %} </ul> |
{% if %} | Conditional statement. | {% if user.is_authenticated %} <p>Welcome, {{ user.username }}!</p> {% else %} <p>Please log in.</p> {% endif %} |
{% elif %} | Conditional elif clause. | {% if value < 10 %} <p>Less than 10</p> {% elif value < 20 %} <p>Less than 20</p> {% else %} <p>20 or more</p> {% endif %} |
{% else %} | Conditional else clause. | {% if user.is_authenticated %} <p>Welcome, {{ user.username }}!</p> {% else %} <p>Please log in.</p> {% endif %} |
{% block %} | Define a block that can be overridden in child templates. | {% block content %} <p>Content goes here.</p> {% endblock %} |
{% extends %} | Inherit from another template. | {% extends "base.html" %} |
{% include %} | Include another template within the current one. | {% include "navbar.html" %} |
{% load %} | Load a custom template tag library. | {% load custom_tags %} |
{% comment %} | Comment out a block of text. | {% comment %} This is a comment and will not be rendered. {% endcomment %} |
{% csrf_token %} | Generate a CSRF token. | <form method="post"> {% csrf_token %} <!-- form fields --> </form> |
{% static %} | Generate a URL for static files. | <img src="{% static 'images/logo.png' %}" alt="Logo"> |
{% url %} | Generate a URL for a view. | <a href="{% url 'app_name:view_name' %}">Link</a> |
{% now %} | Display the current date and time. | <p>Today's date is {% now "Y-m-d" %}</p> |
{% with %} | Create a new context variable. | {% with total=business.employees.count %} <p>Total employees: {{ total }}</p> {% endwith %} |
{% autoescape %} | Control auto-escaping behavior. | {% autoescape off %} {{ data|safe }} {% endautoescape %} |
{% spaceless %} | Remove whitespace between HTML tags. | {% spaceless %} <div> <span>Content</span> </div> {% endspaceless %} |
{% cycle %} | Cycle among values for each iteration of a loop. | <ul> {% for o in some_list %} <li class="{% cycle 'odd' 'even' %}">{{ o }}</li> {% endfor %} </ul> |
{% firstof %} | Output the first variable that is not empty. | {% firstof var1 var2 var3 %} |
{% regroup %} | Group a list of objects by an attribute. | {% regroup items by category as grouped_items %} <ul> {% for group in grouped_items %} <li>{{ group.grouper }} <ul> {% for item in group.list %} <li>{{ item.name }}</li> {% endfor %} </ul> </li> {% endfor %} </ul> |
{% verbatim %} | Disable template tag parsing for a block of text. | {% verbatim %} {{ raw_variable }} {% endverbatim %} |
template inheritance¶
- The most powerful and complex – part of Django’s template engine is template inheritance.
- Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override.
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<title>{% block title %}My amazing site{% endblock %}</title>
</head>
<body>
<div id="sidebar">
{% block sidebar %}
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog/">Blog</a></li>
</ul>
{% endblock %}
</div>
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
blog.html
{% extends "base.html" %}
{% block title %}My amazing blog{% endblock %}
{% block content %}
{% for entry in blog_entries %}
<h2>{{ entry.title }}</h2>
<p>{{ entry.body }}</p>
{% endfor %}
{% endblock %}
blog_page.html
{% extends "base.html" %}
{% block title %}Django is awesome {% endblock %}
{% block content %}
<div>
Django’s template language is designed to strike a balance between power and ease. It’s designed to feel comfortable to those used to working with HTML. If you have any exposure to other text-based template languages, such as Smarty or Jinja2, you should feel right at home with Django’s templates.
</div>
{% endblock %}
Custom template filters¶
-
Create a
templatetags
directory- Django will look for custom filter or tags in directory
app/templatetags
- Create custom filters module
custom_filters.py
- Django will look for custom filter or tags in directory
my_app/
templatetags/
__init__.py
custom_filters.py
- Add custom filters to the module
app/templatetags/custom_filters.py
like below
from django import template
register = template.Library()
@register.filter(name='multiply')
def multiply(value, arg):
"""Multiplies the value by the arg."""
return value * arg
- Load and use custom filters in template
{% load custom_filters %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Custom Filters</title>
</head>
<body>
<h1>Custom Template Filters Example</h1>
<p>Multiply 5 by 3: {{ 5|multiply:3 }}</p>
</body>
</html>
Custom template tags¶
-
Create a
templatetags
directory- Django will look for custom filter or tags in directory
app/templatetags
- Create custom filters module
custom_tags.py
- Django will look for custom filter or tags in directory
my_app/
templatetags/
__init__.py
custom_tags.py
- Add custom filters to the module
app/templatetags/custom_tags.py
like below
from django import template
register = template.Library()
@register.simple_tag
def current_time(format_string):
"""Returns the current time formatted according to the format_string."""
from datetime import datetime
return datetime.now().strftime(format_string)
- Load and use custom filters in template
{% load custom_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Custom Tags</title>
</head>
<body>
<h1>Custom Template Tags Example</h1>
<p>Current time: {% current_time "%Y-%m-%d %H:%M:%S" %}</p>
</body>
</html>