How does the `divisibleby` filter determine if a number is divisible by another number, and what conditions are commonly used?

Calendar 👁️ 71

The template engine of AnQiCMS provides a powerful and flexible tool for the dynamic display of website content. Among which,divisiblebyThe filter is a small but effective feature that can enhance the logic of templates, mainly used to determine if one number can be evenly divided by another.Understand and make good use of this filter, which can help us achieve more intelligent effects in content presentation and page layout.

divisiblebyThe core function of the filter is to determine whether a number is divisible by another number.

divisiblebyThe filter, as the name implies, is primarily used to check whether a given number can be evenly divided by another number.When we need to trigger a conditional judgment based on the divisibility of numbers, this filter becomes particularly useful.

Its basic usage syntax is very intuitive:{{ 数值 | divisibleby: 除数 }}. Here,数值It is the original number we need to judge, while除数Then is the other number we use for integer division. This除数It can be either a fixed number written directly or a variable obtained in another way.

After executing this filter, it will return a boolean value (i.e., true or false):

  • If数值Can be divided by除数Divisible, the filter will returnTrue.
  • If数值Cannot be divided by除数Divisible, the filter will returnFalse.

For example,{{ 21 | divisibleby: 3 }}will returnTrueBecause 21 is divisible by 3; and{{ 22 | divisibleby: 3 }}it will returnFalseThis feature makes it very efficient for conditional judgments in templates.

divisiblebyCommon application scenarios of filters

divisiblebyFilters have a variety of flexible applications in the operation of website content, especially in dealing with lists or repetitive elements, where they can help us achieve more precise control.

  1. List style alternation (zebra line effect)When displaying a list of articles, product lists, or table data, in order to improve readability and visual appeal, we often need to make adjacent rows or columns have different background colors or styles, which is what we call the 'zebra striping' effect. By combiningdivisiblebyFilters andforNested in the loopforloop.Counter(Loop counter) variable, we can easily achieve the requirement of 'changing colors every N lines'.For example, make odd and even rows have different styles, or set a special background every three rows.

  2. Content grouping and inserting specific elementsImagine a long product list page where you want to automatically insert a promotional advertisement, a special recommendation spot, or a visual separator after displaying every 4 products. By judgingforloop.CounterWhether it can be divided by 4, we can insert custom HTML structure or content at the appropriate loop position.This can effectively interrupt the user's reading fatigue and also increase the exposure opportunities of marketing content.

  3. Periodically display special tips or iconsSometimes, we may wish to add some additional marks to the content under certain conditions.For example, in a video list, a 'Hot Recommendation' icon is displayed every 5th video;Or in the news list, a link to the 'latest comment' is displayed every 10 news articles.divisiblebyThe filter makes it simple to enhance this periodic content without complex data processing logic

  4. Custom grid layout and responsive design assistanceWhen building a grid-based layout, for example, you want to display 3 or 4 elements per row,divisiblebyCan assist in determining when to end the current line or start a new one, ensuring that elements are aligned correctly across different screen sizes.Although most modern CSS frameworks have built-in comprehensive grid systems, they are still effective in assisting judgment with template logic in certain scenarios that require fine control.

Code examples and practice

Below, we will demonstrate through some specific code examples,divisiblebyThe use of filters in AnQiCMS templates.

Suppose we have a list of articles.archivesWe want to achieve the following effect:

  • The background color of each article line alternates (different colors for odd and even rows).
  • After displaying 3 articles, a separator or advertisement space is inserted.
<style>
    .article-item {
        padding: 10px;
        margin-bottom: 5px;
    }
    .article-item.odd {
        background-color: #f9f9f9; /* 奇数行背景色 */
    }
    .article-item.even {
        background-color: #e6e6e6; /* 偶数行背景色 */
    }
    .separator {
        border-top: 1px dashed #ccc;
        margin: 20px 0;
        text-align: center;
        color: #888;
    }
</style>

<div class="article-list">
    {% archiveList archives with type="list" limit="10" %}
        {% for item in archives %}
            {# 判断奇偶行,实现斑马线效果 #}
            <div class="article-item {% if forloop.Counter | divisibleby: 2 %}even{% else %}odd{% endif %}">
                <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
                <p>{{ item.Description | truncatechars:100 }}</p>
                <small>发布日期: {{ stampToDate(item.CreatedTime, "2006-01-02") }}</small>
            </div>

            {# 每显示3篇文章后插入分隔线,但不在最后一篇文章后插入 #}
            {% if forloop.Counter | divisibleby: 3 and not forloop.Last %}
                <div class="separator">--- 更多精彩内容 ---</div>
            {% endif %}
        {% empty %}
            <p>目前没有文章。</p>
        {% endfor %}
    {% endarchiveList %}
</div>

In this example,forloop.CounterIt starts from 1 and increments to represent the current loop count.

  • {% if forloop.Counter | divisibleby: 2 %}Determine if the current loop iteration can be divided evenly by 2 to add for even rowsevenclass, add for odd rowsoddClass.
  • {% if forloop.Counter | divisibleby: 3 and not forloop.Last %}Then determine if the current loop count is divisible by 3 and is not the last item in the list, so that a new item is inserted after every third article.separatorofdiv.

By such a combination, we can achieve a rich and diverse display of content and layout requirements without changing the data source and backend logic.

Summary

divisiblebyThe filter is a very practical tool in the AnQiCMS template engine, which provides a flexible solution for complex list display, content grouping, and dynamic layout through simple division judgment. Whether it is the "zebra line" effect to optimize user experience or the periodic element insertion to improve content operation efficiency,divisiblebyCan help us achieve these goals in a concise and efficient manner.Master and flexibly apply this filter, and it will take your AnQiCMS website content management and front-end display to a new level.

Frequently Asked Questions (FAQ)

1.divisiblebyCan the filter only be used for numbers?Yes,divisiblebyThe filter is specifically used to handle variables of numeric type. If it is attempted to be applied to non-numeric types (such as strings), it may cause template rendering errors or unexpected results.Make sure you provide numbers to the filter in actual use.

2. How can you determine if a number cannot be divided evenly?If you need to determine if a number cannot be divided evenly by another number, you can combinedivisiblebythe filter meetsifIn logical judgmentnotKeyword. For example:{% if not forloop.Counter | divisibleby: 2 %}It can be determined whether the current loop counter is an odd number (i.e., not divisible by 2).

3.divisiblebythe filter meetsforloop.CounterWhat is the relationship? divisiblebyFilters are often used withforin the loopforloop.CounterVariables are used together.forloop.CounterIn each loop iteration, it increments and provides the current number of iterations. By usingforloop.CounterasdivisiblebyThe "value" parameter can conveniently implement conditional judgment based on the number of loops, such as alternating row colors, inserting content every N items, etc., which is one of its most common application scenarios.

Related articles

How to set default values for `default` and `default_if_none` filters to avoid displaying blank when the variable is empty or `nil`?

In daily website content management, we often encounter such situations: certain variables may be empty due to unfilled content, missing data, or other reasons (or in programming terms, `nil`).If not handled, these variables may be displayed as blank areas on the front-end page, which not only affects the beauty of the page but may also confuse visitors and reduce the professionalism of the website.AnQiCMS (AnQiCMS) is well aware of this pain point

2025-11-08

How do the `date` and `time` filters display `time.Time` type time values in a specified format?

In AnQi CMS template design, flexibly displaying dates and times is a key aspect of content presentation.In order to meet this refined requirement, AnQi CMS provides a series of practical time processing tools, among which the `date` and `time` filters are important functions for formatting and displaying `time.Time` type time values.

2025-11-08

How to remove specified characters from any position in the string using the `cut` filter in the Anqi CMS template?

In website content operation, we often need to process strings, such as cleaning up extra characters, or standardizing the display content.AnQiCMS template engine provides a series of powerful filters to help us complete these tasks, among which the `cut` filter is a very practical tool, specifically used to remove specific characters from any position in a string.### Understanding the working principle of the `cut` filter The `cut` filter plays a very direct role in the AnQi CMS template

2025-11-08

How to use the `count` filter to calculate the number of times a keyword appears in a string or array?

In website content operation, we often need to understand the frequency of certain specific keywords appearing in articles, product descriptions, and other text.This is very valuable for SEO optimization, content quality analysis, and even just data statistics.AnQi CMS provides a powerful and flexible template system, which includes a very practical `count` filter, which can help us easily achieve this goal.### Understanding the `count` filter In simple terms, `count`

2025-11-08

How can the `dump` filter be used in the template development process for debugging and viewing the structure and value of variables?

During the development of Anqi CMS templates, we often need to handle various dynamic data.This data may come from a database, system configuration, or user input, and it is passed to the template as variables for display.However, sometimes the results displayed by the page are not what we expect-a field may be empty, the data format is incorrect, or the elements contained in a set may not be as expected.In this case, efficiently "viewing" the internal structure, type, and specific values of variables becomes the key to troubleshooting and speeding up development progress

2025-11-08

What security escaping features do the `escape`, `e`, and `escapejs` filters provide when outputting HTML or JavaScript code?

It is crucial for the safety of output content in website operations.Especially when displaying user-submitted data or information obtained from external sources, if not properly processed, websites are easily vulnerable to cross-site scripting attacks (XSS) and other threats.AnQiCMS as a content management system that focuses on security, provides a powerful security escaping mechanism at the template rendering level, among which the `escape`, `e`, and `escapejs` filters are the key tools to ensure output security.AnQiCMS's template engine draws inspiration from Django

2025-11-08

How to enable or disable automatic escaping for specific code blocks in templates using the `autoescape` tag?

In AnQi CMS template development, how to balance flexibility and security when handling dynamic content is an important consideration.Amongst, the HTML automatic escaping mechanism (`autoescape`) plays a key role, which is aimed at preventing cross-site scripting (XSS) attacks, while also allowing us to display native HTML content when needed.Understand and master the usage of the `autoescape` tag, which will make your template creation more skillful.Understanding automatic escaping

2025-11-08

The `safe` filter in Anqi CMS template, when and why to use it to cancel the default escaping of HTML content?

Master the `safe` filter in AnQiCMS templates: unlock the correct rendering and safety boundaries of HTML content AnQiCMS, as an enterprise-level content management system based on Go language, adopts syntax similar to Django template engine in template design, which provides great flexibility for content display.When building website content, we often need to display the information edited on the backend on the front-end page.

2025-11-08