How to effectively use `if` and `for` tags for conditional judgment and data looping in AnQiCMS templates?

Calendar 👁️ 65

In the template development of AnQiCMS,ifandforLabels are undoubtedly the core tool for building dynamic content and achieving flexible layouts.They allow us to display content based on specific conditions, or efficiently iterate over data, thereby transforming static templates into feature-rich, user-demanding pages.AnQiCMS uses a syntax similar to the Django template engine, making these operations intuitive and powerful.

ifLabel: The art of conditional judgment

When you need to decide whether to display an element on the page or display different content based on a certain condition,ifThe label comes into play. Its basic structure is very clear, it can handle simple true and false judgments, and can also deal with complex multi-branch logic.

The simplest form is to check if a variable exists or is true:

{% if archive.Thumb %}
    <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}">
{% endif %}

Here, if the documentarchivehas a thumbnailThumbIf so, the image will be rendered. This judgment can be applied to any variable, such as checking if a list is empty, if a string has content, or if a boolean value istrue.

If you need more detailed control, when the condition is not met, you can provide alternative content, you can useelse:

{% if archive.Thumb %}
    <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}">
{% else %}
    <img src="/static/images/placeholder.png" alt="无图">
{% endif %}

This way, if the article does not have a thumbnail, we can elegantly display a placeholder image.

For more complex scenarios, such as when navigating menus need to distinguish between the current page, parent pages with sub-menus, or other regular pages,if-elif-elsethe structure can come into full play:

{% if item.IsCurrent %}
    <li class="nav-item active"><a href="{{ item.Link }}">{{ item.Title }}</a></li>
{% elif item.HasChildren %}
    <li class="nav-item has-dropdown"><a href="{{ item.Link }}">{{ item.Title }}</a></li>
{% else %}
    <li class="nav-item"><a href="{{ item.Link }}">{{ item.Title }}</a></li>
{% endif %}

Here, item.IsCurrentanditem.HasChildrenIt is a common boolean attribute in navigation list items, indicating whether the item is the current page or has a submenu.By such condition judgment, we can apply different styles or behaviors to navigation items in different states.

ifTags support various comparison operators, such as equal (==), not equal (!=), greater than (>), less than (<), greater than or equal (>=), less than or equal to (<=). In addition, you can useand/orfor logical combination, as well asnotfor logical NOT operation. For example, to judge a number range or the satisfaction of multiple conditions at the same time.

forLabel: Efficiently looping data

The core of a website is usually the display of content lists, whether it is an article list, product list, or navigation menu, similar structures need to be rendered repeatedly.forTags are born for this, they allow you to easily traverse array or slice and other collection types of data.

BasicforThe loop syntax is as follows:

{% for item in archives %}
    <div class="article-card">
        <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
        <p>{{ item.Description }}</p>
        <span>发布时间: {{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
    </div>
{% endfor %}

In this example,archivesIt may be a pass througharchiveListThe article list obtained by the tag. Eachitemrepresents an article object in the list, we canitem.Title/item.Linkin this way to access various properties of the article.

In order to better control the loop process,forThe tag also provides several practical built-in variables:

  • forloop.Counter: The current loop index, starting from1start counting.
  • forloop.Revcounter: The remaining loop count (including the current one), counted down from the total.

These variables are very useful when special styles need to be applied to the first or last item in the loop:

{% for item in archives %}
    <li class="{% if forloop.Counter == 1 %}first-item{% endif %}">
        <a href="{{ item.Link }}">{{ item.Title }}</a>
    </li>
{% endfor %}

When you retrieve data from the database, the list may sometimes be empty. To avoid the page from being blank or showing errors,forTags provide aemptythe clause will execute when the collection in the loop is empty,emptythe content inside:

{% for item in archives %}
    <div class="article-card">
        <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
    </div>
{% empty %}
    <p>当前没有可用的文章。</p>
{% endfor %}

Furthermore,forTags also supportreversedandsortedThe modifier allows you to adjust the order of loops at the template level.reversedIt will traverse the collection in reverse order.sortedIt will attempt to sort the collection (usually for numbers or comparable strings).

{# 倒序显示文章列表 #}
{% for item in archives reversed %}
    ...
{% endfor %}

{# 排序后显示文章列表 #}
{% for item in archives sorted %}
    ...
{% endfor %}

ifandforThe application of combinations: building complex layouts

ifandforThe true power of tags lies in their combined use. By using nested loops or adding conditional judgments within loops, we can build extremely flexible and dynamic page structures.

A typical scenario is to build a multi-level navigation menu. Imagine a main navigation with sub-items under each main item, and these sub-items may be associated with articles under a certain category:

{# 假设 navs 是通过 navList 标签获取到的主导航列表 #}
<ul class="main-nav">
    {% for mainItem in navs %}
        <li class="{% if mainItem.IsCurrent %}active{% endif %}">
            <a href="{{ mainItem.Link }}">{{ mainItem.Title }}</a>
            {% if mainItem.NavList %} {# 检查是否有子导航 #}
                <ul class="sub-nav">
                    {% for subItem in mainItem.NavList %}
                        <li class="{% if subItem.IsCurrent %}active{% endif %}">
                            <a href="{{ subItem.Link }}">{{ subItem.Title }}</a>
                            {% if subItem.PageId > 0 %} {# 假设 PageId 大于0表示关联到分类 #}
                                {% categoryList categories with parentId=subItem.PageId %} {# 获取该分类的子分类 #}
                                    {% if categories %}
                                        <ul class="third-nav">
                                            {% for thirdItem in categories %}
                                                <li><a href="{{ thirdItem.Link }}">{{ thirdItem.Title }}</a></li>
                                            {% endfor %}
                                        </ul>
                                    {% else %}
                                        {# 如果没有子分类,尝试显示该分类下的文档 #}
                                        {% archiveList products with type="list" categoryId=subItem.PageId limit="5" %}
                                            {% if products %}
                                                <ul class="third-nav">
                                                    {% for product in products %}
                                                        <li><a href="{{ product.Link }}">{{ product.Title }}</a></li>
                                                    {% endfor %}
                                                </ul>
                                            {% endif %}
                                        {% endarchiveList %}
                                    {% endif %}
                                {% endcategoryList %}
                            {% endif %}
                        </li>
                    {% endfor %}
                </ul>
            {% endif %}
        </li>
    {% endfor %}
</ul>

This complex example shows how to combinenavList/categoryListandarchiveListtags, utilizeifdetermine whether the navigation item is current, whether it has child items or associated categories, as well asforLooping nested traversal of multi-level structures. Through such combinations, you can build any required navigation or content display logic.

When processing content in templates, especially like article detailsitem.ContentThis is a rich text field, AnQiCMS defaults to HTML escaping to prevent security issues. If you are sure that the content is safe and you want the browser to parse it as HTML rather than plain text,

Related articles

How to dynamically generate a guestbook form with custom form field types using the `guestbook` tag?

It is crucial to provide a convenient user communication channel in modern website operations, and a message board is one of the efficient ways to do so.AnQiCMS (AnQiCMS) fully understands this need, through its powerful template tag system, especially the `guestbook` tag, allowing you to dynamically generate guestbook forms on your website flexibly, and easily customize form fields to meet various business scenarios.

2025-11-07

How to display article comments using the `commentList` tag and integrate reply and like functions?

When building a vibrant website, the article comment feature is undoubtedly a core element to enhance user interaction and promote the development of a content community.AnQiCMS as an efficient and flexible content management system, provides us with powerful template tags, making it simple and intuitive to integrate and display comments.Today, let's delve into how the `commentList` tag in AnQiCMS helps us display article comments and cleverly integrate reply and like functions.

2025-11-07

How to build a complex document parameter filtering interface using the `archiveFilters` tag, such as real estate, product filtering?

In website operation, providing users with an efficient and accurate content filtering function is the key to improving user experience and content discoverability.Whether it is complex real estate information, massive product SKUs, or professional industry documents, a well-designed filtering interface can allow users to quickly locate the information they need.In Anqi CMS, the `archiveFilters` tag is a powerful tool for building such complex filtering interfaces.### Understand the core of the filter interface: content model and custom parameters Build a flexible filtering function

2025-11-07

How to implement the switch of multilingual sites and the setting of default language package in AnQiCMS?

A deep analysis of AnQiCMS multi-language site switching and default language package settings In today's global internet environment, website support for multiple languages has become a key factor in expanding the market and improving user experience.AnQiCMS as a system dedicated to providing an efficient and customizable content management solution also offers flexible and powerful multilingual support.This article will elaborate on how to implement multi-language site switching in AnQiCMS, as well as the setup of the default language package.

2025-11-07

How `list` and `split` filters convert a string to an array and how to process it in a template?

In the powerful template system of Anqi CMS, flexible data processing is the key to building dynamic websites.At times, the data we retrieve from the backend, such as tags, keywords, or custom field values, may be stored as comma-separated strings, but we want to treat them as individual items in the frontend template.At this point, the `list` and `split` filters provided by Anq CMS are particularly important, as they help us convert strings into arrays, thereby enabling more refined control and display in templates.Why do we need to convert a string to an array

2025-11-07

How does the `slice` filter accurately extract the specified part of a string or array for display?

In the daily content management of Anqi CMS, we often need to accurately trim the text or data list displayed on the website to better adapt to different layouts, provide content previews, or optimize the user reading experience.At this point, the `slice` filter has become a very practical tool, which can help us flexibly extract the specified part of a string or array.### Core Function: Basic Usage of `slice` Filter The `slice` filter is like a tailor, capable of cutting according to the "scissors" position you provide

2025-11-07

How do the `truncatechars` and `truncatewords` filters control the truncation display of long text and add an ellipsis?

In website content operation, we often encounter such situations: In order to maintain the neatness and consistency of the page layout, we need to truncate the long text, such as in article lists or product summaries.If cut off simply and brutally, it may not only result in incomplete meaning of the text, but may also destroy the text structure containing HTML tags, affecting the aesthetics and functionality of the page.AnQi CMS, with its flexible template engine, provides us with an elegant solution to this problem.Through built-in text filters, we can easily control the display length of long texts and add ellipses at appropriate positions

2025-11-07

How do the `urlize` and `urlizetrunc` filters automatically convert URLs in text to clickable links?

It is crucial to present information efficiently and aesthetically in website content operations.Especially when the content contains a large number of URLs or email addresses, manually converting them into clickable links is not only inefficient but also prone to errors.AnQiCMS (AnQiCMS) is well-versed in this, its template system provides the practical filters `urlize` and `urlizetrunc`, which can automatically identify URLs in text and intelligently convert them into clickable hyperlinks, greatly enhancing user experience and content management efficiency.###

2025-11-07