Templates

What are Django templates?

Django templates allow us to write HTML and CSS in separate files and render those files using Django.

The syntax to render a template:

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

A template contains variables, which get replaced with values when the template is evaluated, and tags, which control the logic of the template.

How to create Django templates

  1. Create a folder called templates in our app directory
  2. Create a folder called blog (our app’s name) within that, and then add a file called index.html.
├── templates
│   └── blog
│       └── index.html
  1. Edit blog/index.html file

For example

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Blog</title>
    </head>
    <body>
        <h1>Blog Home!</h1>
    </body>
</html>

Variables

The syntax for variable is {{ variable }}.

When the template encounters a variable, it evaluates that variable and replaces it with the result.

We can use a dot (.) to access attributes of a variable.

Example

{{ post.title }} will be replaced with the title attribute of the post object.

Filters

You can modify variables for display by using filters.

{{ value|filter_value }}
  1. length This filter returns the length of the value. It works for both strings and lists : {{ value|length }}

  2. lower This converts text to lowercase: {{ name|lower }}

  3. join This joins a list with commas and spaces: {{ list|join:", " }}

  4. date Check the date filter here

For example, to show published date with format August 10, 2020, we code: `{{ post.date|date:“F d, Y }}

Tag

The syntax for Django tag is {% tag %}

Tags create text in the output, performing loops or logic, and loading external information.

Some tags require beginning and ending tags: {% tag %} ... content ... {% endtag %})

URL tag

We don’t need to hard-code the link in Django but can use tag instead.

For example, to include the link in navbar

<a class="nav" href="{% url 'blog-about' %}">About</a>

if, elif, and else

If, elif, and else condition evaluates a variable. If that variable is True, the contents of the block are displayed:

{% if age >= 18 %} Exam time: {{ adult_exam.time }} {% elif age < 18 && age > 10 %} Participants should be prepare soon! {% else %} You are too young to participate. {% endif %}

For loop

For loop loops over each item in an array.

Example 1: To display a list of tasks

  1. In the views.py:
from django.shortcuts import render

tasks = ["foo", "bar", "baz"]

# Create your views here.
def index(request):
    return render(request, "tasks/index.html", {
        "tasks": tasks
    })
  1. In the tasks/index.html:
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Tasks</title>
    </head>
    <body>
        {% for task in tasks %}
            <li>{{ task }}</li>
        {% endfor %}
    </body>
</html>

Example 2: Display blog post

  1. In the views.py:
from django.shortcuts import render

posts = [
    {
        'author': 'Anna',
        'title': 'Blog post 1',
        'content': 'First post content',
        'date': 'August 10, 2020'
    },
    {
        'author': 'Jane',
        'title': 'Blog post 1',
        'content': 'First post content',
        'date': 'August 1, 2020'
    }
]

def index(request):
    context = {
        'posts': posts
    }
    return render(request, 'blog/index.html', context)
  1. In the blog/index.html:
<!DOCTYPE html>
<html lang="en">
    <head>
        {% if title %}
            <title>My Blog - {{ title }}</title>
        {% else %}
            <title>My Blog</title>
        {% endif %}
    </head>
    <body>
        {% for post in posts %}
            <h1>{{ post.title }}</h1>
            <p>By {{ post.author }} on {{ post.date }}</p>
            <p>{{ post.content }}</p>
        {% endfor%}
    </body>
</html>

If we access localhost:8000/blog, we’ll see:

Blog post 1
By Anna on August 10, 2020

First post content

Blog post 1
By Jane on August 1, 2020

First post content

If we view pagesource:


<!DOCTYPE html>
<html lang="en">
    <head>
        
            <title>My Blog</title>
        
    </head>
    <body>
        
            <h1>Blog post 1</h1>
            <p>By Anna on August 10, 2020</p>
            <p>First post content</p>
        
            <h1>Blog post 1</h1>
            <p>By Jane on August 1, 2020</p>
            <p>First post content</p>
        
    </body>
</html>

Comments

To comment-out part of a line in a template, use the comment syntax: {# #}.

For example, this template would render as ‘hello’:

{# greeting #}hello

Template inheritance

Django template inheritance allows us to build a base template that contains general structure and defines blocks that child templates can override.

3 Steps to use tempate inheritance

  1. Create a base.html template that contains all the common elements of your site.
  2. Create different html template for each page of your site. For example: index.html, about.html. These templates all extend base.html and include section-specific styles/design.
  3. Create individual templates for each page, such as a news article or blog entry.

Example

For example, we create blog/base.html

<!DOCTYPE html>
<html lang="en">
    <head>
        {% if title %}
            <title>My Blog - {{ title }}</title>
        {% else %}
            <title>My Blog</title>
        {% endif %}
    <body>
        {% block content %}
        {% endblock %}
    </body>
</html>

Our blog/index.html becomes

{% extends "blog/base.html" %}

{% block content %}
    {% for post in posts %}
        <h1>{{ post.title }}</h1>
        <p>By {{ post.author }} on {{ post.date }}</p>
        <p>{{ post.content }}</p>
    {% endfor%}
{% endblock %}

Explanation:

  • A block is a section where child template can override.
  • The extends tag indicates that this template “extends” another template, so the template system will locate the parent – “base.html”.

Styling

We can include .css and .script file in blog/static directory.

  1. Create static directory in blog
  2. create a blog directory in static
.
├── blog
│   ├── static
│   │   └── blog
│   │       └── main.css
│   ├── templates
│   │   └── blog
│   │       ├── about.html
│   │       ├── base.html
│   │       └── index.html
  1. To include this styling in our HTML file, we add the line {load static} at the top of base.html. It signals to Django that we wish to have access to the files in our static folder.

  2. In our base.html, link CSS file in the head section:

<link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}">