Django Templates

Django allows you to build powerful dynamic websites. Much of that power and flexibility comes from it’s ability to use templates. Templates in Django are a way to display data to your users. The template is a text file that defines the structure or layout of an HTML page, it uses placeholders and special syntax to represent actual content.

To use templates, you need to create a template file and a view to render the template. In the example below I’ll show how to use a function based view to render a template with user information:

# views.py
from django.shortcuts import render

def home_view(request):
    """View function for home page of site"""

    context = {
        "name": "Thando",
        "last_name": "Moyo"
        "age": 21,
        "hobbies": ["hiking", "wood working", "swimming"]
    }
    
    return render(request, 'index.html', context)

The second line imports the render() shortcut function to generate an HTML file using a template and data. The first part of the view function creates a Python dictionary called context. This context data is what will get plugged into the template later. At the end of the view we call the render() function to create an HTML page and return the page as a response.

render() accepts the following parameters:

  • a request object — This is the same request object that is passed to the view.
  • an HTML template — This is the HTML file to render or plug with the placeholder data in the context
  • a context variable — The context contains the data that will be inserted into the HTML template

In this example, we hard coded the values passed to the context but in a real website this data will likely come from a database.

Templates

Django uses special syntax called template tags that allow you to build dynamic websites quickly. With Django template tags, you can plug Python things like loops and logic into HTML. For example, to print a variable from Python in HTML you use double curly braces with the name of the variable inside. You will see this in action shortly.

Django’s templating system supports template inheritance. Template inheritance allows you to build a base or blueprint template that has all the common elements of your site and defines blocks that the child templates can override. Let’s create a base template, base.html:

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Templates Example</title>
</head>
<body>
    {% include 'navbar.html' %}
    {% block content %}
    {% endblock %}
</body>
</html>

This template creates a skeleton page that includes a navigation bar at the top and an empty content block. The child templates will fill the navbar and the ‘content’ block sections with content. The {% include 'navbar.html' %} is a way of including a template inside another. This is an example of a template tag. The
{% block content %}..{% endblock %} block will be filled with content from a child template, index.html which we will create now:

{% extends 'base.html' %}

{% block content %}
    <h1>Hello world</h1>
    <p>Hello {{ name }} {{ lastname }}. Welcome to the site</p>
    <p>You are {{ age }} years old and your hobbies are:
      <ul>
        {% for hobby in hobbies %}
            {{ hobby }}
        {% endfor %}
      </ul>
    </p>
    
{% endblock %}

The {% extends 'base.html' %} line is how we make a child template inherit from another. In this case, we are extending or inheriting from ‘base.html‘ template.

rendered html

Granted, that is not the most beautiful home page but you can see how we have 1) a navigation bar at the top, and 2) a custom welcome message for the user. These two sections were populated by child templates. The first paragraph in the block plugs the user’s name and last name into the HTML. We defined these values in the context in the view.

In the second paragraph, we use a loop to loop through and list the user’s hobbies. Notice that the for loop tag is different from the one used to display variables. The for tag has a curly brace and a percentage symbol. Django Template Language has powerful built in filters that allow you to format text in many different ways. For example, to capitalise the first letter of each of the hobbies do this:

{% extends 'base.html' %}

{% block content %}
    <h1>Hello world</h1>
    <p>Hello {{ name }} {{ lastname }}. Welcome to the site</p>
    <p>You are {{ age }} years old and your hobbies are:
      <ul>
        {% for hobby in hobbies %}
            {{ hobby|capfirst }}
        {% endfor %}
      </ul>
    </p>
    
{% endblock %}

The highlighted line is an example of a filter. This filter capitalises the first letter in each hobby. The end result is:

Rendered html with dynamic data plugged in

There are many more built in filters and tags you can use, you can even create your own.

Thank you for reading. If you liked this post, please subscribe or follow me on Twitter to get notified of future posts.

0 comments on “Django TemplatesAdd yours →

Leave a Reply