How can you use modulo operation to insert a specific HTML structure after every N elements in an article list?

English translation: As an experienced website operation expert, I am more than happy to delve into how to use modulo operation in AnQiCMS to inject more vitality and features into your article list.


English CMS Operation Advanced: How to skillfully use modulus operation to insert a specific HTML structure after every N elements in the article list?

In the daily operation of website content, we often encounter such needs: on article lists or product display pages, we hope to insert an advertisement, a special recommendation slot, a user guidance information, or simply to break the visual monotony, adding some unique design elements to the list.If manually modifying the article list on each page, it is undoubtedly a time-consuming and labor-intensive task.While AnQiCMS (AnQiCMS) has powerful template functions, combined with a little bit of 'math magic'—modulus operation, everything can be realized automatically and intelligently.

Why should you insert a specific HTML structure in the middle of the article list?

Imagine that when users browse your article list, if the page only presents one article summary after another, without visual changes or interactive features, it is easy to cause aesthetic fatigue and even miss the "eggs" or important information you have prepared meticulously. By inserting HTML structures at specific locations, we can achieve a variety of operational purposes:

  1. Improve user experience and design sense:When the list is too long, periodically inserting banners, separators, or cards of different styles can effectively alleviate visual fatigue, making the page layout more hierarchical and aesthetically pleasing.
  2. Optimize business conversion:Strategically integrate advertising slots (such as Google AdSense), promotional banners, and popular product recommendations into the article stream, which can naturally increase exposure and click-through conversions without interrupting the user's reading rhythm.
  3. Enhanced Content Marketing:Inserting "related topics
  4. A/B testing and data analysis:You can even perform A/B testing based on different N values or insertion content, analyzing which insertion strategy can bring higher user engagement or conversion rate.

Understanding modulus operation and the loop mechanism of AnQiCMS

Modulo operation (%In simple terms, it is to find the remainder. For example,7 % 3The result is1Because 7 divided by 3 leaves a remainder of 1; and6 % 3The result is0Because 6 divided by 3 is an exact division. It is this characteristic that makes the modulus operation a powerful tool for operating on every Nth element.

In AnQiCMS template language, we usually use{% for item in list %}This structure is used to loop through the article list. Inside this loop, AnQiCMS provides several very practical built-in variables, whereforloop.Counteris our core tool.forloop.CounterRepresents the current number of iterations, starting from 1.

Therefore, if we want to process every N elementsafterInsert a block of HTML code, we can think about it like this: Whenforloop.CounterThe value ofN/2N/3N... at this point, insert code. This meansforloop.Counterdivided byNthe remainder is0.

Hands-on practice: Insert an HTML structure after every N elements in the article list

Now, let's demonstrate this process with a specific example.We have an article list and we want to insert a special recommended HTML module every 3 articles.

Firstly, you need to locate the template file used to render the article list. This is usually/template/{您的模板目录}/{模型table}/list.htmlor/template/{您的模板目录}/index/index.htmletc.

In this template file, you will find similar{% archiveList archives ... %}and{% for item in archives %}This loop structure. We will use it inside the loop.forloop.CounterAnd modulo operations to insert custom content.

{# 假设我们正在一个文章列表页面,这里用 archiveList 获取文章列表 #}
{% archiveList archives with type="page" limit="10" %}
    <ul class="article-list-container">
    {% for item in archives %}
        {# 这是每一篇常规文章的HTML结构,例如显示标题和简介 #}
        <li class="article-item">
            <a href="{{ item.Link }}">
                <h3>{{ item.Title }}</h3>
                <p>{{ item.Description|truncatechars:100 }}</p>
            </a>
            <span class="views">{{ item.Views }} 阅读</span>
        </li>

        {# 核心逻辑:使用取模运算判断是否是第3、6、9...个元素 #}
        {% if forloop.Counter % 3 == 0 %}
            {# 重要的是,当 forloop.Counter 等于列表总数时,我们通常不希望再插入额外的结构。 #}
            {# 所以这里再加一个条件:确保不是列表的最后一个元素。 #}
            {% if forloop.Counter != archives|length %}
                <li class="special-insert-item">
                    <div class="promotion-box">
                        <h4>🔥 热门推荐:不容错过的精彩!</h4>
                        {# 这里可以放置任何您想插入的HTML内容,例如一个广告、一个专题链接等 #}
                        {# 我们可以利用AnQiCMS的其他标签来填充动态内容 #}
                        {% archiveList relatedArticles with type="related" limit="1" %}
                            {% for relatedItem in relatedArticles %}
                                <a href="{{ relatedItem.Link }}" target="_blank">
                                    <img src="{{ relatedItem.Thumb }}" alt="{{ relatedItem.Title }}">
                                    <p>{{ relatedItem.Title }}</p>
                                </a>
                            {% else %}
                                <p>了解更多:<a href="/category/hot-topics" target="_blank">热门专题</a></p>
                            {% endfor %}
                        {% endarchiveList %}
                        {# 如果您想插入固定的联系方式信息,可以使用 contact 标签 #}
                        {# <p>联系我们:{{ contact with name="Cellphone" }}</p> #}
                    </div>
                </li>
            {% endif %}
        {% endif %}

        {# 使用 {{- 和 -}} 来移除标签本身产生的空白行,保持HTML输出的整洁 #}
    {%- endfor %}
    </ul>
{% endarchiveList %}

In this code block:

  • We first use{% archiveList archives ... %}Get article data.
  • {% for item in archives %}Loop through each article.
  • Inside the loop,forloop.Counter % 3 == 0Determine if the current article is the 3rd, 6th, 9th... one.
  • forloop.Counter != archives|lengthIt is to avoid inserting extra structure at the end of the list (for example, if the list only has 3 articles, the third one is the last, we usually do not want to insert an empty module after it).
  • In{% if %}Condition is true, we inserted a tag with.special-insert-itemclass:<li>.<li>It contains another.promotion-box, where you can fill in any HTML content according to your needs.
  • To demonstrate, we specifically used{% archiveList relatedArticles ... %}Get an article and display its thumbnail and title, which is the powerful feature of AnQiCMS template tags.
  • Finally, note that the code uses{%- endfor %}Here,{%-and-%}This is a feature provided by AnQiCMS template engine to remove blank lines, which can help you generate more compact and unnecessary space-free HTML code, avoiding unnecessary code redundancy.

Advanced Application and Precautions

  1. Change insertion frequency (N value):Just need to modifyforloop.Counter % N == 0ofNThen it will be.% 5 == 0.
  2. Insert different types of content:You can choose according toforloop.CounterThe value, even inserting different types of HTML structures. For example,.{% if forloop.Counter % 3 == 0 %}Insert ads.{% elif forloop.Counter % 5 == 0 %}Insert subscription button.
  3. CSS style control:To ensure the inserted HTML structure looks coordinated and beautiful, it is necessary to define a unique CSS for it