Templates

To include templates we can use from django.shortcuts import render. The templates directory and template back-end must be declared in setting.configure:

settings.configure(
    ROOT_URLCONF=__name__,
    DEBUG=True,
    SECRET_KEY="secret",
    TEMPLATES=[
        {
            "BACKEND": "django.template.backends.django.DjangoTemplates",
            "DIRS": [Path(__file__).parent / "templates"]
        }
    ]
)

Note

If we want to use a different backend for templates, such as Jinja2, we can simply change the value of “BACKEND” in settings:

'BACKEND': 'django.template.backends.jinja2.Jinja2',

With this, we can update index function to use render, which takes a a request object and a template name as parameters:

def index(request):
    return render(request, "index.html")

Template Inheritance

Context

The variables and data that are accessible from the templates is referred to as the context (which is related to the Django Context Processors). When creating a view function in Django, we have to pass the required context to the return value in order to access it in HTML:

Django URLs

Caution

If any element in a context lookup chain is missing, the object being passed to the template will fail silently - it simply will not display on the site to avoid showing errors to users.

Dynamic links

Filters

We can filter the data being passed into a template by using built-in filters - these work the same in Jinja2 or Django templates and look as follows:

      <p>{{ post.date_added|date:"DATE_FORMAT"}}</p>
      <p>{{ post.body|truncatewords:10 }}</p>