'question php to django simple loop increasing
I have to convert some php code to python django. In django I noticed that it is difficult to make things like php does.
I have to increase a simple loop by **n ( step) *** iteration,
php code:
<?php $step = 3; for($i=0; $i < count($items); $i += $step){ /* */}
In django template:
I tried a for loop of a dictionary:
data['posts'] = {
"comments": [
{"id": "1", "title": "hey buddy"},
{"id": "2", "title": "hey buddy"},
{"id": "4", "title": "hey buddy"},
{"id": "5", "title": "hey buddy"},
{"id": "6", "title": "hey buddy"},
{"id": "7", "title": "hey buddy"},
{"id": "8", "title": "hey buddy"},
{"id": "9", "title": "hey buddy"},
]
}
and in template:
for elem in posts.items:
{{ forloop.counter0|add:"3" }}
This works, but it is only display, not set the loop counter to each iteration to 3.
I want that each iteration, the loop will increase by a specified number.
EDIT so the result i want in django template is:
<div> the first 3 items </div>
<div> the next 3 items (so +3) </div>
<div> the final 3 items (+3) </div>
Solution 1:[1]
I resolved without creating a custom tag in django, just used divisibleby.
Example:
{% if forloop.counter0|divisibleby:3 %}
output items divide into 3 groups
{% endif %}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vinzee |
