How to Use the Cycle Tag in Django



Python


In this article, we show how to use the cycle tag in Django.

Before we go into how to use the cycle tag, what is the cycle tag and what can it allow us to achieve?

The cycle tag is a tag that allows us to perform certain code after a specified number of iterations through the for loop.

Let's say you want a class added to a row after every 3 rows on a table. You can use the Django cycle to add in this code after 3 rows of a table.

Another example of using the cycle tag. Let's say that we have a table. Let's say you want 3 columns in each row. And then after the 3 columms, you want to start a new row.

Another example is let's say you want to create a break every 3 objects of the for loop. You can use a cycle tag to insert an HTML hr tag to create a horizontal line break.

These are some of the applications of the cycle tag in Django.

So now let's go over how to do this in code.

So, in the example below, we insert an HTML insert an HTML hr tag after every 3 objects in the for loop.



So we have a for loop that loops through photos on the website.

After every 3 photo objects, the cycle tag will insert a horizontal line break (hr tag).

The cycle tag goes inside of a for loop and it executes its code after a certain iterations that you specify.

After you declare tag, each '' represents an iteration through the for loop. You can see have 2 empty quotes ('' '') and then we have, '<hr>'. So after the third iteration, the cycle tag will insert a horizontal line break.

Now let's do one more example of the cycle tag in Django.

Let's create a table that has 3 objects per row.

This is shown in the code below.



So we have a for loop again.

Outside of the for loop, before it begins, we declare a table and we declare a tr tag, indicating a row.

Inside of the for loop, we start a column with the td tag.

We have one of our photo objects.

We then use the cycle tag to end the row after 3 iterations through the for loop. We then start a new row.

So this the practicality and use of the Django cycle tag.

It's very useful if you don't want to run straight through a for loop. If you want to insert code after a certain amount of iterations, then the cycle tag is very valuable in these cases.

And this is how to use the cycle tag in Django.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...