How can you determine in a template if a number can be evenly divided by another number?

Calendar 👁️ 69

In website content display, we often encounter situations where we need to adjust the layout or style according to the divisibility of numbers, such as setting different background colors for the odd and even rows of a table, or starting a new row for grouping display every fixed number of contents.In the AnQi CMS template system, implementing such logical judgments is quite direct and efficient.

The AnQi CMS template engine is designed to be very flexible and easy to use, it adopts a syntax structure similar to Django templates, allowing us to access variables through simple references ({{ 变量名 }})and logical control tags({% if ... %}/{% for ... %}) to build dynamic content. In addition, it provides a rich set of filters (filters) for processing and transforming variables, including a utility specifically designed to check for divisibility by numbers.

Core solution:divisiblebyFilter

For determining whether a number can be evenly divided by another number, Anqi CMS provides us with a very convenient and powerful tool:divisiblebyFilter. This filter is used to check if a number can be perfectly divided by another number, i.e., the remainder of the division is zero.

Its basic usage is after the numeric variable to be judged, through the pipe character|连接divisiblebyfilter, and use a colon:Specify another number as the divisor. The syntax structure is roughly as follows:

{{ 被检查的数字 | divisibleby: 整除数 }}

When the number being checked can be perfectly divided by the divisor, the filter will returnTrue(true); otherwise, if it cannot be divided, it will returnFalse(false). For example,{{ 21|divisibleby:3 }}will returnTruewhile{{ 22|divisibleby:3 }}it will returnFalse.

Actual application example

MastereddivisiblebyThe use of filters, we can easily implement various logical controls based on the divisibility of numeric integers in the template.

Scenario one: alternating styles of table rows.

This is a very common requirement, by assigning different CSS classes to the odd and even rows of a table, we can improve the readability of the table. When looping through list content, we can useforThe built-in loop offorloop.Countervariable (indicating the current loop index, starting from 1) to judge.

<table>
    <thead>
        <tr>
            <th>序号</th>
            <th>文章标题</th>
            <th>发布日期</th>
        </tr>
    </thead>
    <tbody>
        {% for item in archiveList %}
            <tr class="{% if forloop.Counter|divisibleby:2 %}even-row{% else %}odd-row{% endif %}">
                <td>{{ forloop.Counter }}</td>
                <td>{{ item.Title }}</td>
                <td>{{ stampToDate(item.CreatedTime, "2006-01-02") }}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>

In this piece of code, we check the loop counterforloop.CounterCan be divided by 2. If it can, it means the current is an even line, applyeven-rowclass; if it cannot, it means it is an odd line, applyodd-rowClass.

Scenario two: content list grouping display

Assuming you want to start a new line every 3 articles (div class="row"),to present a three-column layout, making the content more visually tidy. This is very practical in product displays or image-text list pages.

<div class="container">
    {% for item in archiveList %}
        {# 每隔3个项目或在第一个项目时开启新行 #}
        {% if forloop.Counter == 1 or forloop.Counter0|divisibleby:3 %}
            <div class="row">
        {% endif %}

        <div class="col-md-4">
            <div class="article-card">
                <h4>{{ item.Title }}</h4>
                <p>{{ item.Description }}</p>
                <a href="{{ item.Link }}">查看详情</a>
            </div>
        </div>

        {# 每隔3个项目或在最后一个项目时关闭当前行 #}
        {% if forloop.Counter|divisibleby:3 or forloop.Last %}
            </div> {# 关闭 div.row #}
        {% endif %}
    {% endfor %}
</div>

Here we cleverly utilizeforloop.Counter(starting from 1) andforloop.Counter0(Counting from 0) CooperationdivisiblebyFilter to determine when to open a new line and when to close an old line. Whenforloop.Counter0A number divisible by 3 (i.e., the 0th, 3rd, 6th… element), or when it is the first element, we start a newdiv.row. At the same time, whenforloop.CounterThe number is divisible by 3 or it is the last element (forloop.Last), we close the currentdiv.row, to ensure the integrity of the layout.

Scenario three: combined variable dynamic judgment

divisiblebyThe filter can not only be used for hard-coded numbers, but it also works well with variables in the template.For example, you can obtain the number of articles displayed per row from the system settings and use it as the divisor.

{% set articles_per_row = system.articles_per_row %} {# 假设系统设置中有此变量,值为3或4等 #}

<div class="container">
    {% for item in archiveList %}
        {% if forloop.Counter == 1 or forloop.Counter0|divisibleby:articles_per_row %}
            <div class="row">
        {% endif %}
        <div class="col-md-{{ 12|divisibleby:articles_per_row }}"> {# 动态计算列宽 #}
            <div class="product-item">
                <h3>{{ item.Title }}</h3>
                <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
            </div>
        </div>
        {% if forloop.Counter|divisibleby:articles_per_row or forloop.Last %}
            </div>
        {% endif %}
    {% endfor %}
</div>

In this example,articles_per_rowIs a variable obtained from the system configuration, which makes the grouping logic more flexible and controllable, without modifying the template code you can adjust the layout. At the same time, we also demonstrated12|divisibleby:articles_per_rowThis usage, but pay attentiondivisiblebyThe filter itself returns a boolean value, here you should use ordinary division, for example12 / articles_per_rowTo dynamically calculate the column width. Ifarticles_per_rowIs 3, then the column width is 4.

Cautionary notes and **practice

While usingdivisiblebyWhen filtering, there are several points to note:

  1. Input type:Ensure that the parameter passed todivisiblebyThe number of the filter is a valid numeric type. Normally, template variables will be processed correctly, but if an unexpected situation occurs, please check the output value of the variable.
  2. Readability:Even though template code can be written compactly, proper indentation and comments are still good practices for team collaboration and future maintenance.
  3. Combined with other logic: divisiblebyThe filter returns a boolean value, which means it can be directly embedded into{% if ... %}tags, and can also be combined with other logical operators (such asand/or/not) to build more complex conditional judgments.
  4. Use loop variables wisely: forLoop

Related articles

What happens when the `add` filter performs mixed addition and type conversion fails?

In the AnQi CMS template world, we often use various filters to process data, making the page display more flexible.Among them, the `add` filter is a very practical tool that allows us to add or concatenate two values.In most cases, its performance is very intuitive: when numbers are added to numbers, mathematical operations are performed;When two strings are added together, a simple text concatenation is performed.When a number is added to a string, it also cleverly converts the number to a string and concatenates it, for example, `{{ 5|add:"CMS" }}` results in `5CMS`

2025-11-08

The `add` filter supports mixing which types (integer, float, string) for addition?

In AnQiCMS template development, we often need to combine or calculate different data, especially when displaying dynamic content.Among them, the `add` filter is a very practical tool, allowing us to flexibly add values of numeric and string types.Understand how it works, which can help us build templates more efficiently and accurately.### `add` filter: Flexible addition of numbers and strings The `add` filter plays the role of 'addition' in the AnQiCMS template engine

2025-11-08

How can arithmetic operations such as addition, subtraction, multiplication, and division be performed directly in the template?

In AnQiCMS, templates are the cornerstone of displaying website content.Make flexible use of templates, not only can it make the content display more colorful and varied, but also some built-in functions can achieve dynamic effects.Among them, performing arithmetic operations directly in the template is a very practical feature that many users may overlook but is very useful.It allows us to process numbers directly in the front-end template without writing additional backend code, performing operations such as addition, subtraction, multiplication, and division, thereby realizing more dynamic display effects or logical judgments.The AnQiCMS template system borrows the syntax from the Django template engine

2025-11-08

How to round off floating-point numbers or round up/down in Anqi CMS template?

When using Anqi CMS for website content management, we often encounter scenarios where precise control of numbers is required, especially when it comes to floating-point numbers such as prices and statistics, where rounding up or down is particularly important.The Anqi CMS template engine provides flexible filters that can help us easily achieve these requirements.There is no direct 'ceil' or 'floor' function tag, but by reasonably utilizing existing functions, we can still achieve the purpose.### One, using `floatformat`

2025-11-08

How to get the Nth digit from the end of a number using the `get_digit` filter?

During the template creation process of Anqi CMS, we often need to handle data flexibly so that the most user-friendly information can be displayed on the front-end page.Numbers are a common form of data, and sometimes we may need to extract a specific number from a longer number.At this point, the `get_digit` filter can be put to use, which can help us easily obtain the Nth digit from the end of a number.### The core function and purpose of the `get_digit` filter The `get_digit` filter is as its name suggests

2025-11-08

What will the `get_digit` filter return if the position it accesses does not exist?

In AnQi CMS template development, flexibly using various filters (filters) can greatly enhance the efficiency and accuracy of content display.`get_digit` filter is one of the practical tools used to process numeric data.It allows us to extract a specific digit from a number accurately.However, a common issue during usage is: What will the `get_digit` filter return if the position being accessed exceeds the length of the number itself?### `get_digit`

2025-11-08

How to format numbers, strings, and any other values to output as strings in a specific format (`stringformat`)?

In the display of website content, we often need to present different types of data (such as numbers, strings, and even more complex structures) in a unified and precise manner on the page.The template engine of AnQiCMS provides powerful tools, one of which is a very practical feature called `stringformat` filter, which can help us format any value into a string of a specific format.When we retrieve data from the backend, whether it is the number of views of an article, the price of a product, or user-defined parameters, they may be represented by numbers

2025-11-08

Which formatting placeholders does the `stringformat` filter support?

In AnQiCMS template development, in order to better display and control the presentation of data on the page, we often need to format variables.Among them, the `stringformat` filter is a very practical tool that allows us to convert numbers, strings, or other types of values into a specific string format according to predefined rules.The strength of this filter lies in its adoption of the placeholder syntax of the Go language `fmt.Sprintf()` function, making the control of output format flexible and accurate

2025-11-08