Django 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 template’s logic.
How to create Django templates
- Create a folder called
templatesin our app directory - Create a folder called
blog(our app’s name) within that, and then add a file called index.html.
├── templates
│ └── blog
│ └── index.html
- Edit the
blog/index.htmlfile
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 the 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 }}
length This filter returns the length of the value. It works for both strings and lists :
{{ value|length }}.lower This converts text to lowercase:
{{ name|lower }}.join This joins a list with commas and spaces:
{{ list|join:", " }}.date Check the date filter here
For example, to show the published date with the 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, perform loops or logic, and load 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 a tag instead.
For example, 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
- 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
})
- 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
- 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)
- 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 template inheritance
- Create a base.html template containing all your site’s common elements.
- Create a 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.
- 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 the child template can override.
- The
extendstag 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.
- Create a static directory in the blog.
- create a blog directory in static.
.
├── blog
│ ├── static
│ │ └── blog
│ │ └── main.css
│ ├── templates
│ │ └── blog
│ │ ├── about.html
│ │ ├── base.html
│ │ └── index.html
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.In our base.html, link the CSS file in the
headsection:
<link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}" />