In AnQiCMS template, how to determine if one number can be evenly divided by another to achieve conditional display?

Calendar 👁️ 68

In Anqi CMS template development, we often need to display content based on specific conditions, such as adding a special style every few elements in a list or inserting separators at specific positions.When this condition is to judge whether a number can be evenly divided by another number, the powerful template engine of Anqi CMS provides a concise and efficient solution.

The AnQi CMS template system adopts syntax similar to the Django template engine, making it very intuitive to handle such logical judgments. To determine if one number can be evenly divided by another, we mainly use the 'filter' function in the template, especiallydivisiblebyfilter.

Core function:divisiblebyFilter

divisiblebyThe filter is designed specifically to check the divisibility of numbers. Its function is to determine whether a number can be evenly divided by another number and returns a boolean value (True or False).This filter greatly simplifies the logic we use to make such judgments in the template.

Its basic usage is very intuitive:

{{ 待判断的数字 | divisibleby: 除数 }}

For example, if you want to know if a number10can be divided by2divisible, you can write it like this:

{{ 10 | divisibleby: 2 }}

This will outputTrue. If the number is11then, it will output.False.

combined with conditional judgment to achieve flexible display

Knowing whether a number is divisible is not enough, what we need more is to use this result to achieve conditional content display. At this point, it is necessary to combine the conditional judgment tags in the Anqi CMS template.{% if %}.

Suppose we have a list of articles.archivesWe hope to insert a special ad position or clear the float after displaying three articles. This is very useful when creating a multi-column layout. We can take advantage offorthe built-in loop.forloop.CounterA variable that represents the current loop index, starting from 1.

Below is an example of inserting an element in an article list, after displaying three articles.divAn example of an element to clear the float:

<div class="article-list">
    {% for article in archives %}
        <div class="article-item">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
            <p>{{ article.Description }}</p>
        </div>

        {# 判断当前文章序号是否能被3整除,如果是,则插入清除浮动的div #}
        {% if forloop.Counter | divisibleby: 3 %}
            <div class="clearfix"></div> {# 用于清除浮动或插入特定内容 #}
        {% endif %}
    {% endfor %}
</div>

In this example,forloop.Counter | divisibleby: 3It willforloop.CounterReturn when it is a number like 3, 6, 9, etc.Truethus triggeringdiv.clearfixdisplay.

Another common scenario is to apply different styles to odd and even rows in a list to improve readability or visual effects. This can also be achieved bydivisiblebyTo implement a filter:

<ul class="product-list">
    {% for product in products %}
        <li class="product-item {% if forloop.Counter | divisibleby: 2 %}even{% else %}odd{% endif %}">
            <img src="{{ product.Thumb }}" alt="{{ product.Title }}">
            <h4>{{ product.Title }}</h4>
        </li>
    {% endfor %}
</ul>

Here, whenforloop.CounterWhen the number is even (2, 4, 6...), it will addeventhe class; when the number is odd (1, 3, 5...), then addoddClass.

modulus operator%as an alternative option

exceptdivisiblebyFilter, you can also use the traditional modulus operator%to make the same judgment. The modulus operator returns the remainder after dividing two numbers. If the remainder is0, it means that it can be divided evenly.

For example:

{# 使用模运算符判断10是否能被2整除 #}
{% if 10 % 2 == 0 %}
    <p>10能被2整除</p>
{% endif %}

In terms of function,divisiblebyFilters andX % Y == 0the judgment is equivalent. However, in the template,divisiblebyFilters are generally considered more readable because they directly express the intention of 'whether it is divisible', and the code looks simpler.

Expansion of practical application scenarios

This divisibility judgment logic is widely used in website operations and template design:

  • Grid layout adjustmentCreate responsive layouts by dynamically inserting clearing floats or line-end markers based on the number of elements displayed per row (for example, 4 elements per row on PC and 2 elements per row on mobile).
  • Content grouping displayFor example, after every 5 news content, insert a 'View More' link or switch to a new display module.
  • Special promotion or event displayIn the product list, every Nth product displays a 'Time-limited discount' or 'Hot' tag.
  • Page style optimizationIn some custom pagination components, it may be necessary to adjust the style or display content based on the parity or a special divisibility rule of the current page number.

Bydivisiblebythe filter meetsifThe combination of tags, the template engine of AnQi CMS provides great flexibility for website developers, allowing them to easily implement various conditional display requirements based on numerical order, thereby creating a more dynamic and attractive user interface.


Frequently Asked Questions (FAQ)

1.divisiblebyIs the filter only usable for integers?

divisiblebyThe filter is primarily designed to determine the divisibility relationship between integers. Although it may accept floating-point numbers at the lower level, in most cases, the semantics of divisibility judgment occur within the integer range, such as judgment10Can be divided by3not divisible by10.5Can be divided by2.5. When using it, it is recommended to ensure that the number to be judged and the divisor are both integer types to avoid unexpected results.

2. How can I check if a number 'cannot' be divided by another number?

You can simply in{% if %}Add before the statementnotkeywords. For example, if you want toforin the loop, whenforloop.CounterCannot be divided by2Perform some operations when divisible (i.e., odd lines), it can be written like this:

{% if not (forloop.Counter | divisibleby: 2) %}
    {# 这是奇数行才会显示的内容 #}
{% endif %}

3. Can I check multiple divisibility conditions in the same conditional statement?

Can be. Anqi CMS template engine supportsandandorLogical operators, you can use in{% if %}Combine multiple statementsdivisiblebyFilters or other conditions. For example, if you want wheneverforloop.CounterCan be3Divisible and can be divided by5Perform operation when divisible:

{% if (forloop.Counter | divisibleby: 3) and (forloop.Counter | divisibleby: 5) %}
    {# 当序号是15、30等数字时显示 #}
{% endif %}

This makes the conditional judgment of the template more flexible in complex layout and content display logic.

Related articles

What are the differences and applicable scenarios between the `default` and `default_if_none` filters when the template variable is empty?

In AnQi CMS template design, reasonably handling variables that may be empty is the key to ensuring the integrity and smooth user experience of website content display.When a template variable has no value or is in an 'empty' state, we usually do not want blank or error messages to appear on the page, but rather we would like to display a preset default content.At this time, the `default` and `default_if_none` filters provided by Anqicms come into play.They can all provide default values for variables

2025-11-08

How to format Unix timestamp into a readable date and time format in AnQiCMS template?

In website content management, time information plays a crucial role, whether it is the publication date of articles, update time, or the submission time of comments, the record of time is indispensable.Databases usually store these time data in a concise and efficient format - Unix timestamps.However, for the end user, a string of numbers in a timestamp is not as intuitive and easy to understand as “October 27, 2023 14:30”.

2025-11-08

How to remove specific characters or extra spaces from AnQiCMS template variables?

In website content operations, we often encounter such situations: the template variable content retrieved from the database may contain some unnecessary characters, extra spaces, or formats that are not satisfactory.These subtle details, if not handled properly, may affect the aesthetics of the page, user experience, and even cause interference with search engine optimization (SEO).AnQiCMS provides powerful template filtering functionality, helping us easily clean and format these variables.The template syntax of AnQiCMS is similar to Django engine

2025-11-08

How to count the number of times a certain keyword appears in the article content in the AnQiCMS template?

In content operation, understanding the frequency of keywords in articles is an important part of SEO optimization and content strategy analysis.By counting the frequency of keywords, we can better evaluate the density, relevance, and even discover potential optimization spaces.AnQiCMS provides a powerful and flexible template system,配合 its built-in content filter, we can easily count the number of occurrences of specific keywords in the article content.### Understanding the need: Why do we need to count keywords?Count the number of times a keyword appears in an article, mainly including the following practical application scenarios: 1.

2025-11-08

How to quickly view the detailed structure and value of complex variables during debugging in AnQiCMS template?

During AnQiCMS template development, we often need to understand what data and structure a variable contains internally, especially when dealing with complex data objects or debugging template issues.Sometimes, direct output of a variable can only yield a simple value or error message, and cannot delve into its detailed composition.At this point, it is particularly important to master some effective methods for viewing the complete structure and value of variables.### The Challenge of AnQiCMS Template Debugging The template syntax of AnQiCMS is versatile, whether it is the system built-in `archive`

2025-11-08

The `escape` and `escapejs` filters in AnQiCMS are applicable to which HTML/JS escaping scenarios?

In AnQiCMS template development, it is very important to understand and properly use escape filters to ensure website security and correct content display.The system uses a template engine syntax similar to Django, which means it takes some security measures by default when handling variable output.Today, let's talk about the `escape` and `escapejs` filters to see in which scenarios they can be used.

2025-11-08

How to split a line of text content (such as a tag string) into an array of individual words for processing in AnQiCMS?

In the practice of AnQiCMS content management, we often encounter scenarios where it is necessary to split a seemingly simple line of text into smaller, more independent 'words' for fine-grained processing.For example, the document tag (Tag), keyword list, or multiple values separated by a specific symbol in custom fields.The core of this requirement lies in converting a string into an array that can be traversed and manipulated individually.

2025-11-08

How to precisely control the display of floating-point numbers in the AnQiCMS template, such as retaining two decimal places?

In website content operation, the way numbers are presented often affects user experience and the accuracy of information.Especially for floating-point numbers, such as product prices, statistics, and ratings, it is common to require accuracy to several decimal places or rounding according to business needs.AnQiCMS is a powerful template system that provides us with a flexible way to handle these data.Today, let's delve into how to efficiently and accurately control the display of floating-point numbers in the AnQiCMS template.

2025-11-08