Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break "for loop" in Django template

I have this code

    {% for account in object_list %}         <tr>         {% for field, value in book.get_fields %}               <th>{{ field.verbose_name }}</th>          {% endfor %}         </tr>     {{ break }}     {% endfor %} 

I want to break the for loop after first iteration. break is not working

like image 491
tej.tan Avatar asked Jun 28 '11 14:06

tej.tan


People also ask

How do you break a loop in Django?

There is no break in Django template system but you can achieve an statement like break with bellow architecture. (Loop will go iteration but u don't do anything.) 1- Use with to define a variable to determine current status, 2- Use a template custom tag to change statement to negate current status.

What is Forloop counter in Django?

But Django brings in the box an automatically creates a variable called forloop. counter that holds the current iteration index. {% for variable in variables %} {{ forloop.counter }} : {{ variable.variable_name }} {% endfor %} The forloop.

How do I change the value of a variable in a Django template?

We can set the value of a variable in the Django template using with tag. This will output the below content. One downside of this approach is that we have to write the lines where we are accessing the variable inside with and endwith block. Using with is useful when using a costly variable multiple times.


1 Answers

I think you should use slice to achieve your goal

{% for account in object_list|slice:":1" %} 
like image 85
Turikumwe Avatar answered Sep 28 '22 03:09

Turikumwe