Course Content
Django: First Dive
Django: First Dive
DTL Loop
In the previous chapter, you implemented the view function that passes a context with an iterable QuerySet:
The main purpose of DTL (Django Template Language) is to improve and speed up the writing of HTML pages. DTL has various tools, one of which is the loop.
The DTL Loop allows you to iterate over the passed through the context QuerySet.
Usage
To use a loop in templates, you need to use the special DTL syntax:
Let's implement a loop inside the post_list.html
template:
The {% for post in posts %}
syntax initiates a loop that iterates over each object in the posts
QuerySet. The variable post
is created to represent the current object in each iteration.
{{ post.title }}
and {{ post.text }}
display attributes of the current object in iteration.
The {% endfor %}
syntax marks the end of the for
loop. It tells Django to stop iterating over the posts
QuerySet and continue executing the rest of the template code.
In summary, the code iterates over a QuerySet called posts
and generates an HTML container for each post, displaying the post's title and text within separate heading and paragraph elements, respectively.
Result
Thus, DTL provides the ability to dynamically create HTML pages through the for
loop depending on the number of elements. Without DTL, you would have to create HTML pages for each number of posts.
Thanks for your feedback!