How to flexibly control the conditional display and loop output of content in AnQiCMS templates through `if`, `for`, and other logical tags?

Calendar 👁️ 75

In AnQiCMS, the template is the core of building the website's appearance and displaying content.It is crucial to be proficient in using the logical tags in the template to make the content of the website more flexible and intelligent.This is,ifcondition judgment andforLoop output tags are the two great tools for dynamic content display.They allow you to display or hide content based on specific conditions, as well as efficiently traverse and output a series of data, thereby creating highly customized and responsive frontend pages to meet user needs.

The template syntax design of AnQiCMS has borrowed from the Django template engine, so it will be very easy for users familiar with this syntax to get started. Its basic rule is: variables are used with double curly braces{{ 变量名 }}output, while logical tags such as condition judgment and loop control use single curly braces and percentage signs{% 标签名 %}wrap, and these logical tags usually need a corresponding closing tag.

Conditional display:if/elif/elseusefulness

Imagine such a scenario: You want to display a piece of text, an image, or a functional button only under certain conditions, or display different content based on different situations. At this point,ifLogical tags are very useful. They allow you to set conditions in the template, and only when the condition is true will the content wrapped be displayed to the user.

ifThe basic usage of tags is very intuitive:

{% if 条件 %}
    <!-- 当条件为真时显示的内容 -->
{% endif %}

In practice, you may encounter situations where you need to handle multiple conditional branches. The AnQiCMS template provideselif(else if abbreviation) andelsetags, allowing you to build more complex conditional logic:

{% if 第一个条件 %}
    <!-- 当第一个条件为真时显示的内容 -->
{% elif 第二个条件 %}
    <!-- 当第一个条件为假,且第二个条件为真时显示的内容 -->
{% else %}
    <!-- 当所有条件都为假时显示的内容 -->
{% endif %}

Common judgment scenarios include:

  • Check if a variable exists or has a value:For example, you will display the image only when there is a thumbnail in the article.
    
    {% if archive.Thumb %}
        <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}" />
    {% else %}
        <img src="/static/images/default-thumb.png" alt="默认图片" />
    {% endif %}
    
  • Compare the value of variables:For example, display specific information based on the document ID, or judge a certain status value.
    
    {% if archive.Id == 10 %}
        <p>这是ID为10的特别推荐文章!</p>
    {% endif %}
    
    {% if category.ParentId == 0 %}
        <p>这是一个顶级分类。</p>
    {% endif %}
    
  • Boolean value judgment:Some variables are inherently boolean (True/False) and can be used directly for judgment.
    
    {% if item.IsCurrent %}
        <span class="active">当前选中</span>
    {% endif %}
    
  • UseinandnotOperator: Check if a value is contained within a collection (such as an array or list) or determine if a condition is not met.
    
    {# 假设 archive.Flag 包含多个推荐属性标志,如 "h,c,f" #}
    {% if "h" in archive.Flag %}
        <span class="hot-badge">热门</span>
    {% endif %}
    
    {% if not archive.Thumb %}
        <p>此文章暂无缩略图。</p>
    {% endif %}
    

Through these flexibleifLogical combination, you can precisely control the display of each element on the page, greatly enhancing the intelligence and interactivity of the template.

Loop output:forThe powerful functionality of iteration

When you need to display a series of similar content, such as article lists, product lists, navigation menu items, or image sliders, manually writing HTML code one by one will be very inefficient and difficult to maintain. At this time,forThe loop tag becomes your powerful assistant. It allows you to iterate over a data collection (such as byarchiveList/categoryList/navListData obtained by tags, and applies the same template structure to each element in the collection, thereby dynamically generating a large amount of content.

forThe basic usage of tags is:

{% for item in 集合变量 %}
    <!-- 对每一个 item 执行的操作,item 代表集合中的当前元素 -->
{% endfor %}

Traverse common data types:

AnQiCMS many tags will return a data set, for example:

  • archiveListReturn document list.
  • categoryListReturn category list.
  • navListReturn navigation menu list.
  • pageListReturn single page list.
  • tagDataListReturn the document list under a certain tag.

After you use these tags to get the data, you can then go throughforLoop to display them. For example, display the titles of the latest 10 articles:

{% archiveList archives with type="list" limit="10" %}
    <ul>
        {% for article in archives %}
            <li><a href="{{ article.Link }}">{{ article.Title }}</a></li>
        {% endfor %}
    </ul>
{% endarchiveList %}

forloopVariable: Enhanced Loop Control

InforInside the loop, AnQiCMS provides some specialforloopVariable, allowing you to better control the style or behavior of the loop:

  • forloop.Counter: The current iteration number of the loop (starting from 1).
  • forloop.Revcounter: The remaining iteration number of the loop (decreasing from the total number).

These variables are especially useful when you need to add odd/even styles, display numbers, or determine whether it is the first/last element of the list:

<ul>
    {% for item in archives %}
        <li class="{% if forloop.Counter is odd %}odd{% else %}even{% endif %}">
            {{ forloop.Counter }}. <a href="{{ item.Link }}">{{ item.Title }}</a>
            {% if forloop.Counter == 1 %} (最新) {% endif %}
        </li>
    {% endfor %}
</ul>

Special case handling:emptyTag

When you traverse a collection that may be empty, to avoid a blank page, you can useemptytag to provide an alternative content:

{% for item in archives %}
    <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
{% empty %}
    <li>目前还没有任何文章发布。</li>
{% endfor %}

Loop control:reversedwithsorted

AnQiCMS'forTags also supportreversedandsortedkeyword to change the order of traversal:

  • {% for item in archives reversed %}Reverse traverse the set.
  • {% for item in archives sorted %}Traverse the set after sorting it (for numbers or comparable strings).

cycleLabel: alternate display of styles or content.

cycleLabels allow you to output multiple predefined values in order during each loop iteration. This is very convenient when you need to apply alternating CSS classes to list items or cycle through different icons:

<ul>
    {% for item in archives %}
        <li class="{% cycle 'row-a' 'row-b' %}">
            <a href="{{ item.Link }}">{{ item.Title }}</a>
        </li>
    {% endfor %}
</ul>

Here, the list item'sclassIt willrow-aandrow-balternate.

Advanced techniques and precautions

combined useifandfor:Masteredif

Related articles

How does AnQiCMS's `urlize` filter automatically convert URLs and email addresses in plain text to clickable links?

In website content operation, we often need to include some URLs or email addresses in the articles or descriptions.In traditional methods, this information is often just plain text, and users need to manually copy and paste to access it, which undoubtedly increases the user's operation cost and affects the interactivity of the content. 幸运的是,AnQiCMS cleverly goes through its powerful template filter mechanism, providing us with an elegant solution - that is the `urlize` filter.

2025-11-09

How to use the `truncatechars` or `truncatewords_html` filter to truncate text or HTML content and add an ellipsis for display?

When operating a website, we often encounter situations where we need to display long content, but the page space is limited.For example, on the article list page, we usually only want to display the abstract of the article; on the product detail card, we may only want to show a brief description.If this content is not processed, it may overflow the container, destroy the page layout, and affect the user experience.The AnQi CMS knows the importance of content display and provides us with powerful template functions.

2025-11-09

How does AnQiCMS automatically filter or process external links in article content and control their display on the front end?

In content operation, properly handling external links in article content is an important link, it not only concerns the health of the website's SEO, but also affects the reading experience of users.AnQiCMS provides a flexible mechanism to help users automatically filter or process external links, and supports control over the front-end display methods. ### Core Function: Automatic Handling Strategy for External Links AnQiCMS provides convenient settings in the background, allowing users to manage external links in article content according to their own operational strategies.

2025-11-09

How to add categories for image resources in AnQiCMS and manage the front-end display according to categories?

In AnQiCMS (AnQiCMS), effectively organizing and managing your website image resources is the key to improving operational efficiency and front-end display quality.The image classification function not only makes the background management work orderly, but also provides a flexible foundation for the presentation of front-end page content.Below, let's take a detailed look at how to add categories for image resources in AnQiCMS and cleverly manage the display on the front end.

2025-11-09

Does AnQiCMS support displaying a custom shutdown prompt when the website is closed?

The website is in operation, and it is inevitable that there will be situations where the website needs to be temporarily closed, such as system upgrades, data maintenance, or business adjustments, etc.How can you clearly and professionally convey the current status of the website to visitors to avoid them seeing a stiff error page, which is particularly important.For users using AnQiCMS, the good news is that the system has fully considered this point and provided a very flexible setting function for the shutdown prompt information.Yes, AnQi CMS fully supports displaying your custom prompt information when the website is closed.

2025-11-09

How to customize and display category banner images or thumbnails in AnQiCMS to enhance the visual effect?

In website operation, the application of visual elements is crucial for attracting users and enhancing brand image.The category page is an important entry for users to browse content, and if it is equipped with a dedicated Banner image or thumbnail, it will undoubtedly greatly enhance the aesthetics and professionalism of the page.Next, let's see how to achieve this effect in AnQiCMS. ### One, Backend Settings: Configure Exclusive Visual Elements for Categories To add exclusive visual elements to a category, we first need to enter the AnQiCMS backend management interface.

2025-11-09

How to accurately control the timestamp date format display in the `stampToDate` tag of AnQiCMS on the front-end?

Clear, consistent, and beautiful time information display is crucial for user experience in website operation.Whether it is the publication date of the article, the update time of the product, or the deadline of the event, a friendly date and time format always allows visitors to obtain information more quickly.AnQiCMS deeply understands this, providing us with a powerful and flexible template tag - `stampToDate`, which allows us to easily control various date and time formats displayed on the front end.

2025-11-09

How to remove extra blank lines or newline characters in the output content by using the `remove` tag in AnQiCMS?

While developing website templates with AnQiCMS, we often encounter a detail issue that the logic tags (such as `if` condition judgment, `for` loop) in the template may generate unnecessary blank lines or newline characters when rendering output HTML content. These seemingly harmless blanks usually do not affect the final visual presentation of the page, but in some scenarios where code neatness is required or precise control of element spacing is needed, they may bring some minor troubles, such as affecting the readability of the HTML source code

2025-11-09