Django templates for loops and loops

(tl; dr below)

Let me explain what I'm trying to accomplish: I have a two-dimensional array, and I would like to show its contents in a certain way. I want "lines", and each line can display no more than three "objects" due to the lack of a better word. So I want to iterate over the array and create my HTML in the process. My idea is this: each "first of three" elements in the array should open a "string". Each "third of three" elements must close the "line". However, if the last element in the [inner] array is not the "third of three", it should still close the line. So, for example, if we had something like L=[ [0,1,2,3,4], [5,6,7] ], I would like to display it like this:

0  1  2
3  4

5  6  7

What can be marked as:

<div>0 1 2</div>
<div>3 4</div>
<div>5 6 7</div>

My first thought was to simply use the modulo operator and see if each iteration had a “first”, “second” or “third” line, but Django templates did not directly support modulo (more on that later).

So, I came up with the template code as follows:

{% for x in L %}
 {% for y in x %}
  {% cycle '<div>' '' '' %}
   {{ y }}
  {% cycle '' '' '</div>' %}
 {% endfor %}<br/>
{% endfor %}

. , 0 div, 1 , 2 div, 3 4... , t , 4 " 3". , Django , , , , [inner] for, 3 ( ), div:

{% for x in z %}
 {% for y in x %}
  {% cycle '<div>' '' '' %}
   {{ y }}
  {% cycle '' '' '</div>' %}

  {% if forloop.last %}
  {% if forloop.counter|divisibleby:"3" %}
    <!-- Row Already Closed -->
  {% else %}
    </div>
  {% endif %}
  {% endif %}

 {% endfor %}<br/>
{% endfor %}

! . : , Django reset, for. , 5 div , . , , div!

, . , -, Django. - , ?

tl; dr 2d-, . L=[ [0,1,2,3,4], [5,6,7] ] 3 :

0  1  2
3  4

5  6  7

?

+5
1

{% if forloop.counter0|divisibleby:"3" %}, , <div>, {% if forloop.last or forloop.counter|divisibleby:"3" %}, , </div>.

{% for x in z %}
 {% for y in x %}
  {% if forloop.counter0|divisibleby:"3" %}<div>{% endif %}
   {{ y }}
  {% if forloop.last or forloop.counter|divisibleby:"3" %}</div>{% endif %}
 {% endfor %}<br/>
{% endfor %}
+14

All Articles