A standard HTML page consists of hundreds or even thousands of lines — a lot of repetitive work. But what if you need to change a tag or a class of several similar elements? This little problem can spoil the evening if you work on a site.
As a web framework, Django has a convenient way to generate HTML dynamically. The most common approach relies on templates. With Django Template Language (DTL), you can specify the static part of an HTML page, the dynamic data of the page, and also extend any base design for an HTML page.
DTL
DTL is a language that allows you to control the elements of an HTML page on the server side. Templates are files that consist of special syntax constructions and HTML layouts. These constructions allow you to modify the page content before sending it to the client. So templates help you personalize a page directly — for each user, with love.
The work with DTL starts with four fundamental pillars: variables, control expressions, tags, and filters. They are part of the framework. You can also define your filters and tags, but before we get to that, let's figure out what you can get from the box, starting with variables and control expressions.
Templates have programming tools on the page but don't overuse them. View handlers are a better option. Calculate it before sending it to a template if you only need an expression's length. Use DTL if you need both.
To understand how to use the four fundamental pillars, let's consider a project structure as follows:
Suppose there is John Doe, a guy working on a brilliant blog. Every blog starts with the first post and the first impression, so the content needs to be good; we'll leave that to John since our job here is code.
To introduce some examples, create a Django project with any name you like and add the blog application. Define a simple handler to render a template in the blog/views.py module:
from django.views import View
from django.shortcuts import render
blog_title = "John Doe's blog"
first_post = {
"text": "My first post",
"theme": "Easy talk",
"comments": [
"My congratulations!!",
"Looking forward to the second one",
],
}
class MainView(View):
def get(self, request, *args, **kwargs):
context = {"post": first_post, "blog_name": blog_title}
return render(request, "blog/index.html", context=context)Then, paste this template to the blog/templates/blog/index.html file:
<html>
<body>
<h2>{{ blog_name }}</h2>
<div>{{ post.text }}</div>
</body>
</html>We can also pass the value of the model with object_model.field as the context:
from django.shortcuts import render
from .models import Blogs
def index(request):
latest_blogs_list = Blogs.objects.order_by("-publication_date")[:5]
context = {"latest_post_list": latest_post_list}
return render(request, "blog/index.html", context)Do not forget to add blog to your INSTALLED_APPS in the settings.py module, and then add this code to your urls.py module in the project's directory:
from django.urls import path
from blog.views import MainView
urlpatterns = [
path("", MainView.as_view()),
]It's okay if you don't grasp how this code works for now; look through the content of the first_post and blog_title variables.
You can keep using this file later on. Just replace its content when you need it!
Variables
Variables deliver the data to the templates. Usually, all data comes from the controller or views, but you can also define your variables correctly in the template.
Here is what you can pass from the Python code to the template:
primitive types like integers and strings;
common Python structures such as dicts, lists, sets, or tuples;
functions with no extra arguments;
an instance of a custom class.
You can pass any Python object in templates; however, it makes no sense for other types because you cannot use them properly.
To render the variable or its attributes, you should use a special syntax to distinguish DTL from HTML. Put the variable in double curly brackets {{ and }}:
<!-- Accessing a variable -->
<h2>{{ blog_name }}</h2>If you want to access the attributes of the variable, use the dot operator:
<!-- Accessing the value of a dict by key -->
<div>{{ post.text }}</div>It's possible to call the variable's method without extra arguments; the difference is that you don't need round brackets after the call. If you want to capitalize all words in the blog name, call the title method of a string variable {{ blog_name.title }}. Here is an excellent simple example for you:
<h2>{{ blog_name.title }}</h2>Note that when there's no variable passed, it will be None by default
Conclusion
The Django template language provides a simple and efficient method to create dynamic web apps. By mastering its basic syntax and using variables, developers can quickly build flexible and interactive templates while separating presentation from logic.
Understanding Django's template language helps with HTML layout and dynamic content, making web apps more flexible and maintainable.