How to use `for` loop and `if` conditional judgment tags in Anqi CMS template?

As an experienced security CMS website operation personnel, I am very clear about the core role of templates in content presentation.A flexible and efficient template not only enhances user experience but also helps us achieve accurate content placement and management.In the Anqi CMS template system,forloop andifConditional tags are the two foundational elements for building dynamic and interactive web pages. They make content no longer static text blocks, but intelligent display that can change according to data.

Understand the control tags in the Anqi CMS template

The AnQi CMS template engine adopts syntax similar to Django and Blade, making it very easy for content developers to get started. In the template, we use double curly braces{{变量}}Output the value of the variable, while for logical control tags such as loops and conditional judgments, we use single curly braces and percent signs{% 标签 %}These control tags must appear in pairs, that is, there must be a start tag as well as a corresponding end tag, for example{% if 条件 %} ... {% endif %}or{% for item in 集合 %} ... {% endfor %}.

UtilizeforLoop through the data set

forThe loop tag is a key tool in Anqi CMS template used for iterating over arrays, slices, or any iterable data collection.It allows us to dynamically display a series of contents, such as article lists, product albums, category navigation, or friend links, etc.

A basicforThe loop syntax is as follows:

{% for item in 变量集合 %}
    <!-- 在这里输出每一个 item 的内容 -->
{% endfor %}

Inside the loop,itemrepresented by each element of the current iteration set, we can access its internal fields by{{ item.属性名 }}the way. For example, when we usearchiveListtags to get the article list,itemIt represents each article object, we can easily get the title, link, and other information of the article:

{% archiveList archives with type="list" limit="10" %}
    {% for article in archives %}
        <div class="article-item">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
            <p>{{ article.Description }}</p>
            <span>发布日期:{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
        </div>
    {% endfor %}
{% endarchiveList %}

Of Security CMSforLoops also provide some built-in variables and modifiers to enhance their flexibility. For example,forloop.CounterYou can get the current loop index (starting from 1),forloop.RevcounterGet the number of remaining elements. This is very useful when you need to apply special styles to the first or last element of a list.

{% archiveList archives with type="list" limit="5" %}
    {% for article in archives %}
        <div class="article-item {% if forloop.Counter == 1 %}first-item{% endif %}">
            <h3>{{ forloop.Counter }}. <a href="{{ article.Link }}">{{ article.Title }}</a></h3>
        </div>
    {% endfor %}
{% endarchiveList %}

When we need to traverse the data in a different order,reversedandsortedModifiers can be useful.reversedIt will traverse the collection in reverse, whilesortedit will attempt to sort the number set.

{% for num in numberList sorted %}
    <!-- 按升序输出数字 -->
{% endfor %}

{% for article in archives reversed %}
    <!-- 按倒序输出文章 -->
{% endfor %}

Furthermore,forLoops also supportemptyTag. When the collection being traversed is empty or undefined,emptyThe content within the tags will be rendered, not the content within the loop. This is very useful for elegantly handling the situation where there is no content to display:

{% archiveList archives with type="list" categoryId="10" limit="5" %}
    {% for article in archives %}
        <div class="article-item">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
        </div>
    {% empty %}
        <p>当前分类下暂无文章。</p>
    {% endfor %}
{% endarchiveList %}

applyifConditional judgment controls content display

ifConditional tags are the core of implementing logic control in AnQi CMS templates.It allows us to decide based on specific conditions which parts of the page should be rendered and which should be hidden.This is particularly important when building responsive layouts, displaying different content based on user permissions, or handling missing data.

ifThe basic structure of tags includes{% if 条件 %}/{% elif 其他条件 %}(optional) and{% else %}(Optional), and with{% endif %}End:

{% if 条件1 %}
    <!-- 条件1为真时显示的内容 -->
{% elif 条件2 %}
    <!-- 条件1为假且条件2为真时显示的内容 -->
{% else %}
    <!-- 所有条件都为假时显示的内容 -->
{% endif %}

Conditional expressions can include various comparison operators such as==/!=/>/</>=/<=), logical operators such asand/or/not),and check if the variable exists (i.e., its 'truth value').

For example, we can decide whether to display the image based on whether the article has a thumbnail:

{% archiveList archives with type="list" limit="1" %}
    {% for article in archives %}
        <h3>{{ article.Title }}</h3>
        {% if article.Thumb %}
            <img src="{{ article.Thumb }}" alt="{{ article.Title }}">
        {% else %}
            <p>本文没有缩略图。</p>
        {% endif %}
        <p>{{ article.Description }}</p>
    {% endfor %}
{% endarchiveList %}

When dealing with more complex logic,elifandelseProvided the ability to make multi-branch choices. For example, based on theFlagproperties to display different tags:

{% archiveDetail archive %}
    <h1>{{ archive.Title }}</h1>
    {% if "h" in archive.Flag %}
        <span class="flag-hot">热点</span>
    {% elif "c" in archive.Flag %}
        <span class="flag-recommend">推荐</span>
    {% else %}
        <span class="flag-normal">普通</span>
    {% endif %}
    <p>{{ archive.Content|safe }}</p>
{% endarchiveDetail %}

We can also usenotThe operator to determine whether a condition is false. For example, to check if a website is closed:

{% system siteStatus with name="SiteStatus" %}
{% if not siteStatus %}
    <p>欢迎访问我们的网站!</p>
{% else %}
    <p>{{ system with name="SiteCloseTips" }}</p>
{% endif %}

CombinationforandifImplement advanced customization

forloop andifThe true power of conditional tags lies in their combination use.By nesting conditional judgments inside a loop, we can perform refined content display for each element in the data set based on its own attributes or status.

A common scenario is to determine whether a category has subcategories in a category list, thereby rendering different navigation structures:

{% categoryList categories with moduleId="1" parentId="0" %}
    <ul class="main-nav">
        {% for category in categories %}
            <li>
                <a href="{{ category.Link }}">{{ category.Title }}</a>
                {% if category.HasChildren %}
                    <ul class="sub-nav">
                        {% categoryList subCategories with parentId=category.Id %}
                            {% for subCategory in subCategories %}
                                <li><a href="{{ subCategory.Link }}">{{ subCategory.Title }}</a></li>
                            {% endfor %}
                        {% endcategoryList %}
                    </ul>
                {% endif %}
            </li>
        {% endfor %}
    </ul>
{% endcategoryList %}

Another example is to apply different styles to odd or even rows of articles while traversing the article list, or display a "hot" tag based on the article's view count:

{% archiveList archives with type="list" limit="10" %}
    {% for article in archives %}
        <div class="article-card {% if forloop.Counter % 2 == 0 %}even{% else %}odd{% endif %}">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
            {% if article.Views > 1000 %}
                <span class="badge-hot">热门</span>
            {% endif %}
            <p>{{ article.Description }}</p>
        </div>
    {% endfor %}
{% endarchiveList %}

To avoid unnecessary blank lines when rendering templates, we can utilize{%-and-%}syntax to control the whitespace before and after tags. Use it at the beginning of the tag{%-It will remove all leading whitespace and use at the end of the tag-%}It will remove all trailing whitespace. This is particularly important for keeping the generated HTML code clean, although it is not a direct logical tag, but it is an important detail that works in collaboration with them.

Conclusion

In the Anqi CMS template world,forloop andifConditional tags are the foundation for dynamic content display and fine-grained control.By mastering their usage, we can build highly flexible, powerful, and user-friendly website interfaces.Whether it is to display complex article lists, build multi-level navigation, or adjust page elements according to specific conditions, these tags can provide solid technical support for our content operation work and help us better attract and retain users.


Frequently Asked Questions (FAQ)

1. How tofordetermine if the current element is the last one in the loop?

You can useforloop.LastBoolean variable to judge. When the current iteration is the last element in the loop,forloop.LastThe value istrue. For example:

{% for item in collection %}
    <div class="item{% if forloop.Last %} last-item{% endif %}">
        {{ item.Title }}
    </div>
{% endfor %}

2. How to display a friendly prompt instead of a blank when the list is empty?

Inforthe loop, you can use{% empty %}Label to handle this situation. When you try to iterate over an empty or undefined collection,{% empty %}and{% endfor %}The content within will be rendered instead of the loop body itself.

{% archiveList articles %}
    {% for article in articles %}
        <p>{{ article.Title }}</p>
    {% empty %}
        <p>抱歉,目前没有可显示的文章。</p>
    {% endfor %}
{% endarchiveList %}

3. How toifHow to judge multiple conditions in a statement?

You can use logical operatorsandandorto combine multiple conditions.andAll conditions must be true,orAt least one condition must be true. Also, you can usenotto negate a condition.

`twig {% if article.Views > 1000 and 'h' in article.Flag %}

<p>这是一篇高浏览量热点文章!</p>

{% elif article.Views > 500 or “c” in article.Flag %}

<p>这篇文章值得关注。</p>