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.
templates
in our app directoryblog
(our app’s name) within that, and then add a file called index.html.├── templates
│ └── blog
│ └── index.html
blog/index.html
fileFor example
<!DOCTYPE html>
<html lang="en">
<head>
<title>Blog</title>
</head>
<body>
<h1>Blog Home!</h1>
</body>
</html>
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.
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 }}.
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 %})
.
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 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 loops over each item in an array.
from django.shortcuts import render
tasks = ["foo", "bar", "baz"]
# Create your views here.
def index(request):
return render(request, "tasks/index.html", {
"tasks": tasks
})
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tasks</title>
</head>
<body>
{% for task in tasks %}
<li>{{ task }}</li>
{% endfor %}
</body>
</html>
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)
<!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>
To comment-out part of a line in a template, use the comment syntax: {# #}
.
For example, this template would render as ‘hello’:
{# greeting #}hello
Django template inheritance allows us to build a base template that contains general structure and defines blocks that child templates can override.
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:
extends
tag indicates that this template “extends” another template, so the template system will locate the parent – “base.html”.We can include .css and .script file in blog/static directory.
.
├── 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 head
section:
<link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}" />