For Django, use ** built-in tags and filters ** if you want dynamic processing when using template files. For example, IF and For statements, and also extends and blocks. See below for details.
Reference: Built-in Tags and Filters
What I want to do this time is modulo ** in the ** if tag in the template. Below is a sample code.
        {% for user in users%}
            {%if the remainder is 1%}
                <div class="columns is-mobile">
            {% endif %}
            <div class="column">
                <div>
                    ~abridgement~
                </div>
            </div>
            {%if when the remainder is 0%}
                </div>
            {% endif %}
        {% endfor %}
There is a tag that is already provided that returns True if it is divisible like ** divisible by **, but when the remainder is 1, this process, when the remainder is 2, this process ... Can not.
In such a case, you can solve it by preparing ** Customer Template **.
First, create the following directories and files under the project.
project/
 ├ templatetags/
           └ tags.py
And add the following to the `INSTALLED_APPS` of the `` `settings.py``` file
settings.py
INSTALLED_APPS = [
    'project',
]
Edit  tags.py as follows
settings.py
from django import template
register = template.Library()
@register.filter
def modulo(num, val):
    return num % val
Finally, load the tag with the template you want to use the custom template.
{% load templates%} is important.
{% load tags %}
~abridgement~
        {% for user in users%}
            {% if forloop.counter|modulo:3 == 1 %}
                <div class="columns is-mobile">
            {% endif %}
            <div class="column">
                <div>
                    ~abridgement~
                </div>
            </div>
            {% if forloop.counter|divisibleby:"3" %}
                </div>
            {% endif %}
        {% endfor %}
Have a nice Django life, everyone!
Recommended Posts