How to use `if` and `for` tags for logical judgment and loop traversal in AnQiCMS templates?

As an experienced website operations expert, I fully understand the importance of a flexible and powerful template system for content management.AnQiCMS Based on its high-performance architecture based on the Go language and support for Django template engine syntax, it provides us with great convenience.It is not just a tool for publishing content, but also a powerful tool for us to achieve personalized content display and enhance user experience.

In the template world of AnQiCMS,ifandforThe tag is undoubtedly the cornerstone of building dynamic content.They give templates the ability to perform logical judgments and loop traversals, allowing our website content to be presented intelligently according to different conditions, or to display a series of related data in a neat and orderly manner.Today, let's delve into how to skillfully use these two tags in the AnQiCMS template to inject more vitality into your website.


I. The Art of Logic:ifFlexible Use of Tags

In website operations, we often need to display different content based on different business scenarios or data states.For example, when the user logs in, a welcome message is displayed, and when not logged in, a registration/login entry is displayed; or add special style tags based on the "recommended" attribute of the article.iftags become the core tool for conditional judgment for us.

AnQiCMSif标签语法简洁明了,与许多现代模板引擎类似,它支持单条件判断、带Englishelse的二选一判断,以及带Englishelif(else if)的多条件判断。所有ifstatements must end with{% endif %}End.

1. Basic condition judgment:){% if 条件 %}

This is the simplest form, whenifthe following condition is true (true) the content within the tag will be rendered.

{# 假设我们想判断网站名称是否存在,存在则显示 #}
{% if system.SiteName %}
    <h1>欢迎来到 {{ system.SiteName }}!</h1>
{% endif %}

You can use various comparison operators (==equals,!=Not equal to,>Greater than,<Less than,>=greater than or equal to,<=Less than or equal to),as well as logical operators(andand,oror,notNot)to construct complex conditions. For example, to determine if the document ID is 10:

{% if archive.Id == 10 %}
    <p>这是文档ID为10的特别内容。</p>
{% endif %}

2. Two-way decision-making:{% if 条件 %} ... {% else %} ... {% endif %}

When a condition is true, execute some code, otherwise execute another part. This is very useful in handling scenarios with clear 'yes' and 'no' results.

{# 判断文章是否有缩略图,有则显示,无则显示占位图 #}
{% if archive.Thumb %}
    <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}">
{% else %}
    <img src="/public/static/images/placeholder.webp" alt="无图片">
{% endif %}

3. Multi-condition judgment:{% if 条件 %} ... {% elif 其他条件 %} ... {% else %} ... {% endif %}

When you need to handle two or more mutually exclusive conditions,eliftags come in handy. It allows you to add multiple judgment branches in a chain.

{# 根据文档的 Flag 属性显示不同的标签 #}
{% if archive.Flag contains "h" %}
    <span class="badge badge-hot">头条</span>
{% elif archive.Flag contains "c" %}
    <span class="badge badge-recommend">推荐</span>
{% else %}
    <span class="badge badge-normal">普通</span>
{% endif %}

In this example,archive.Flag contains "h"It will determineFlagDoes the string contain the character 'h', if it does, then execute the first segment of code, otherwise continue the judgmentelifof the condition.

4. Check if the variable exists or is empty:

ifLabels can be used naturally to check if a variable exists or if its value is empty (for examplenil, empty strings, empty arrays, etc.).

{# 检查联系电话是否存在 #}
{% if contact.Cellphone %}
    <p>联系电话:{{ contact.Cellphone }}</p>
{% else %}
    <p>暂无联系电话</p>
{% endif %}

Second, the power of iteration:forthe magic of label iteration

A core feature of a dynamic website is its ability to display a series of repeated but different content, such as article lists, product lists, navigation menu items, comment lists, and so on.for标签正是 AnQiCMS 模板引擎中实现这种“循环遍历”功能的关键。它让我们可以轻松地访问数组、切片(slice)或其他可迭代对象中的每一个元素,并针对每个元素进行渲染。

1. Basic loop traversal:{% for item in collection %}

This isforThe most common use of tags, it will iterate overinthe collection after (collection) and assign each element in turn toitemthe variable, and then{% endfor %}The previous code block is rendered.

{# 遍历并显示最新的10篇文章标题和链接 #}
{% archiveList archives with type="list" limit="10" %}
    <ul>
        {% for article in archives %}
            <li>
                <a href="{{ article.Link }}">{{ article.Title }}</a>
            </li>
        {% endfor %}
    </ul>
{% endarchiveList %}

Here,archiveListThe tag obtained a document list and assigned it toarchivesthe variable. Then,forto iteratearchiveseach of themarticleThe object, and rendered the title and link of the article.

2. Handle empty set:{% for item in collection %} ... {% empty %} ... {% endfor %}

In actual operation, we often encounter the situation where a list may be empty.If you loop through an empty list directly, nothing will be displayed on the page, which might confuse the user.for标签提供了一个非常优雅的Englishempty子标签来处理这种情况。当Englishcollection为空或不存在时,English{% empty %}and{% endfor %}之间的内容就会被渲染。English

{# 遍历并显示 Tag 文档列表,如果为空则显示提示信息 #}
{% tagDataList archives with type="page" limit="10" %}
    {% for item in archives %}
        <div class="tag-article">
            <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
            <p>{{ item.Description|truncatechars:100 }}</p>
        </div>
    {% empty %}
        <p class="no-content">当前标签下暂无相关文章。</p>
    {% endfor %}
{% endtagDataList %}

Useempty比先用EnglishifIt is much more concise to judge the length of the list before deciding whether to loop, and it also conforms more to the logical flow of the code.

3. Loop context variable: giving more control to iteration

InforLoop internally, AnQiCMS provides a series of built-inforloopvariables to help us better control the rendering behavior of the loop:

  • forloop.Counter: English: Current iteration number (starting from 1).
  • forloop.Revcounter: Current remaining iterations of the loop (counting down from the total).
  • forloop.First: If it is the first element in the loop, it istrue.
  • forloop.Last: If it is the last element in the loop, it istrue.
  • forloop.Odd: IfCounterIs odd, istrue.
  • forloop.Even: IfCounterIs even, istrue.

These variables are very useful when adding special styles (such as highlighting the first item or changing row colors) to list items, or inserting additional content at specific positions.

`twig {# Utilize forloop variable to add different styles or content to list items #} {% categoryList categories with moduleId=“1” parentId=“0” limit=“5” %}

<ul class="category-nav">
    {% for category in categories %}
        <li class="{% if forloop.First %}first-item{% endif %} {% if forloop.Last %}last-item{% endif %} {% if forloop.Odd %}odd-row{% else %}even-row{% endif %}">
            第 {{ forloop.Counter }} 项:<a href="{{ category.Link }}">{{ category.Title }}</a>
            {% if forloop.Last %}
                <span class="tip">(这是最后一项)</span>
            {% endif %}
        </li>
    {% endfor %}
</ul>

English