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

Calendar 👁️ 62

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>

Related articles

How to use the `tagDataList` tag to display documents under a specified Tag in the AnQi CMS template?

As an experienced CMS website operations manager for a leading security company, I know that high-quality content and convenient user experience are the key to attracting and retaining users.Tags (Tag) serve as an important dimension for content organization, not only helping users quickly find the content they are interested in, but also an indispensable part of internal link optimization and SEO strategy.

2025-11-06

How to use the `categoryDetail` tag to get category details in the AnQi CMS template?

Hello, I am your familiar old friend, a website operator who has been dealing with AnQiCMS for a long time.In daily content management and website optimization work, flexibly using AnQiCMS template tags is the key to improving efficiency and user experience.Today, let's delve deeply into a very practical tag: `categoryDetail`, and see how it helps us obtain detailed category information in the AnQiCMS template.

2025-11-06

How to use the `archiveList` tag in AnQi CMS template to call the document list?

As an expert who has been deeply involved in the field of CMS content operation for a long time, I fully understand the importance of a flexible and efficient template tag for website content display.Among them, the `archiveList` tag is undoubtedly the core tool for calling document lists in the Anqi CMS template.It can not only help us accurately filter and display various types of document content, but also combine multiple parameters to meet the diverse needs of content presentation, thus providing readers with a high-quality browsing experience.

2025-11-06

How are the basic conventions and file directory structure requirements for template creation in AnQi CMS?

As a senior CMS website operation personnel of an enterprise, I know that a clear and standardized template production convention and directory structure is crucial for the long-term operation and maintenance of the website.High-quality templates not only improve user experience, but also lay the foundation for SEO optimization.Next, I will elaborate on the basic conventions and file directory structure requirements of the Anqi CMS document for you.

2025-11-06

How to use the `stampToDate` tag to format timestamps in the Anqi CMS template?

In website content management, the accuracy and aesthetics of time presentation are crucial for user experience.Whether it is the publication date of the article, the update time of the product, or the submission time of the comments, a clear and consistent date format can significantly improve the readability and professionalism of the content.AnQi CMS is an efficient and flexible content management system, deeply understanding this, and provides a powerful and simple tool for template developers - the `stampToDate` tag, which is specifically used to format timestamps into various custom date and time display formats.

2025-11-06

What is the role of the `safe` filter in the AnQi CMS template and when should it be used?

As a professional deeply familiar with the operation of Anqing CMS, I know the importance of template security and the correct presentation of content for a website.In the Anqi CMS template system, the `safe` filter plays a key role, concerning the security and display effect of the website. ### Automatic Escaping Mechanism of AnQiCMS Template AnQiCMS template system draws on the syntax characteristics of the Django template engine, one of its core design philosophies is security.

2025-11-06

How to use `truncatechars` and `truncatewords` in Anqi CMS template?

As a website operator who is well-versed in the operation of AnQiCMS, I deeply understand the subtleties of content presentation.How to elegantly handle the display of text content when building an engaging and user-friendly website experience.AnQi CMS, with its flexible class Django template engine, provides us with powerful content control capabilities, among which the text truncation feature is a commonly used tool for optimizing page layout and improving reading experience.

2025-11-06

How to use `join` and `split` filters to handle strings and arrays in AnQi CMS template?

As an experienced CMS website operation person in Anqi, I am well aware of the importance of flexible data handling in content management and display.The AnQi CMS template engine provides a rich set of filters to help us achieve this goal, among which the `join` and `split` filters are particularly powerful in handling string and array data, allowing our content display to be more dynamic and accurate.

2025-11-06