Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
DTL Loop | Templates
Django: First Dive
course content

Зміст курсу

Django: First Dive

Django: First Dive

1. Get Started
2. Write the First Page
3. Models
4. Working with Database
5. Templates
6. Request Handling

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.

Все було зрозуміло?

Секція 5. Розділ 4
We're sorry to hear that something went wrong. What happened?
some-alt