How to use `if` and `for` tags to flexibly control content display logic?

Calendar 👁️ 65

Unlock the secrets of Anqi CMS content display:ifwithforFlexible use of tags

AnQi CMS is dedicated to providing users with a high-efficiency and customizable content management experience.In website content operation, we often need to display different information based on different conditions, or display a series of contents in bulk.ifLogical judgment tags andforLoop through tags, they are the core for flexible content control.

AnQiCMS's template syntax is similar to Django and Blade, even if you are a beginner, you will find its structure clear and easy to learn. By skillfully usingifandforYou can make the website display a wide variety of content layouts and interaction logic without modifying the core code.

ifTags: allow content to be presented under certain conditions.

Imagine, your website needs to decide whether to display an element based on different user states, article attributes, even whether the data exists.ifThe label is born for this, it allows you to control the visibility of content based on one or more conditions.

ifThe basic usage of tags is very intuitive. You just need to wrap the content that needs to be conditionally displayed in{% if 条件 %}and{% endif %}Between. If the condition is true, the enclosed content will be rendered; otherwise, it will not be displayed.

For example, you may want to display the image only when there is a thumbnail for the article:

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

Hereitem.ThumbIt is a condition that checks whether the article data containsThumba field with a value.

Furthermore,ifTags also supportelif(else if) andelse,Allow you to construct multiple conditional judgments.This is very useful when handling complex business logic.

{% if item.Logo %}
    <img src="{{item.Logo}}" alt="{{item.Title}}">
{% elif item.DefaultLogo %} {# 假设存在一个默认Logo字段 #}
    <img src="{{item.DefaultLogo}}" alt="{{item.Title}}">
{% else %}
    <span>暂无图片</span>
{% endif %}

Besides directly checking if a variable exists or comparing values,ifThe tag can be combined with various filters provided by AnQiCMS for more detailed conditional judgments. For example, you can uselengthThe filter determines if a list is empty or passes throughcontainThe filter determines if a piece of text contains a specific keyword:

{% if categories|length > 0 %}
    <p>当前网站有分类信息。</p>
{% endif %}

{% if archive.Content|contain:"AnQiCMS" %}
    <p>这篇文章提到了AnQiCMS!</p>
{% endif %}

These flexible combinations allowifTags become an indispensable tool for controlling the display logic of content.

forTags: Batch display and loop control

In website operation, list display is one of the most common content forms, whether it is article list, product display, category navigation, or friendship links.forThe tag is used to iterate over a data collection and to render content repeatedly for each item in the collection.

forThe basic usage of a tag is to take each item from a data collection one by one and process it inside a loop:

{% for item in archives %}
    <li>
        <a href="{{item.Link}}">{{item.Title}}</a>
        <p>{{item.Description}}</p>
    </li>
{% endfor %}

here,archivesIt is usually an article list or other data collection,itemIt represents each member of the set, you can accessitemvarious properties (such asTitle/Linketc.) to construct content.

To make the loop more intelligent,forTags providedforloopA variable that contains some useful information about the current loop state. For example,forloop.CounterYou can get the current loop index (starting from 1),forloop.RevcounterCan obtain the index from the end. This is very convenient for applying special styles to the first, last, or specific position elements in a loop:

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

In addition, you can also usereversedUse a modifier to traverse the collection in reverse, or usesorteda modifier (for sortable data) to sort the traversal. When the data set may be empty,emptyLabels can be useful, they allow you to display a prompt message when the collection is empty instead of a blank page:

{% for item in products %}
    <div>{{item.Title}}</div>
{% empty %}
    <p>暂无相关产品。</p>
{% endfor %}

This way, even if there is no product data, users can get friendly feedback.

ifandforThe synergy: building complex logic

ifandforThe use of tags alone is already powerful, but when combined, they can build extremely flexible and complex display logic.A common scenario is to decide how to display based on the specific attributes of each element in a loop.

For example, when rendering a navigation menu, you may want to display the submenu section only when a navigation item contains a submenu:

{% navList navs %}
    {%- for item in navs %}
        <li>
            <a href="{{ item.Link }}">{{item.Title}}</a>
            {%- if item.NavList %} {# 判断当前导航项是否有子导航列表 #}
            <dl>
                {%- for inner in item.NavList %} {# 遍历子导航列表 #}
                    <dd><a href="{{ inner.Link }}">{{inner.Title}}</a></dd>
                {% endfor %}
            </dl>
            {% endif %}
        </li>
    {% endfor %}
{% endnavList %}

This example perfectly demonstratesforLoop through the main navigation, then in each iteration, useifDetermine whether the current navigation item has a sub-navigation(item.NavList) and if so, use it againforLoop through and display sub-navigation items. This nested logic is the basis for building complex structures such as multi-level menus, dynamic content blocks, etc.

Another example is in the article list, if the article is marked as 'Top News', it should have a prominent red title, otherwise maintain the normal style:

{% archiveList archives with type="list" limit="10" showFlag=true %}
    {% for item in archives %}
    <li>
        <a href="{{item.Link}}">
            {% if item.Flag|contain:"h" %} {# 假设“h”代表头条属性 #}
                <h5 style="color: red;">{{item.Title}}</h5>
            {% else %}
                <h5>{{item.Title}}</h5>
            {% endif %}
        </a>
        <p>{{item.Description}}</p>
    </li>
    {% endfor %}
{% endarchiveList %}

Byif item.Flag|contain:"h"We check the article'sFlagWhether the attribute contains 'h' (headlines), thus

Related articles

How to correctly display pagination navigation for articles or category lists?

When managing website content, whether it is an article list, product display, or other category pages, a clear and effective pagination navigation is crucial for improving user experience and search engine optimization.AnQiCMS (AnQiCMS) provides powerful template tag features, allowing us to easily add correct pagination navigation to the list page.This article will introduce how to implement this feature in AnQi CMS.

2025-11-08

How to integrate and display a friend link list on a website?

In website operation, friendship links play an indispensable role. They are not only the bridges to establish contact with other websites but also effective ways to improve website authority, obtain external traffic, and enhance user experience.AnQiCMS as an efficient and flexible content management system provides an intuitive and convenient solution for the integration and display of friend links. ### First Part: Admin Friend Links One of the design philosophies of AnQiCMS is to make website operation more efficient, and the management of friend links is naturally integrated very well.

2025-11-08

How to display the user comment list below the article page?

In website operation, user comments are an important aspect for enhancing content interaction, strengthening community atmosphere, and optimizing search engine rankings (SEO).AnQiCMS provides a flexible and powerful template tag system, making it easy and convenient to integrate a user comment list and comment form at the bottom of the article page.This article will provide a detailed introduction on how to elegantly display user comments on the article detail page of AnQi CMS, and also provide a function for users to submit comments.

2025-11-08

How to retrieve and display detailed descriptions and associated documents for a specific tag?

In content management, tags are a powerful and flexible tool that helps us organize website content more finely, improve user experience, and optimize search engine rankings.AnQiCMS fully understands this, providing intuitive and feature-rich template tags that allow you to easily obtain and display detailed descriptions of specific tags and their associated documents.This article will delve into how to use these tags in the AnQiCMS template to make your website content more relevant and discoverable.### Understand the tags in AnQiCMS In

2025-11-08

How to format timestamp data into a readable date and time format and display it?

In website operation and content management, we often need to handle various data, among which date and time information is particularly common.However, these data are often stored in a string of seemingly unordered numbers (i.e., timestamps), which is difficult for ordinary users to understand intuitively.AnQiCMS as an efficient enterprise-level content management system fully considers this user's needs, provides a concise and powerful way, helps us convert these timestamp data into a clear date and time format, and present it on the website.AnQiCMS's template engine design借鉴了 Django in English

2025-11-08

How to customize website structured data (JSON-LD) to improve search engine display?

It is crucial to make the website content stand out in the search engine results page (SERP) in today's highly competitive online environment.Structured data, especially JSON-LD format, is the key tool to achieve this goal.It helps search engines better understand the content of the page, thereby giving them the opportunity to display richer and more attractive "rich media summaries" (Rich Snippets), such as the publication date of the article, the author, ratings, product prices, etc., which can significantly increase click-through rates.

2025-11-08

How to display language switch options on the front-end page and support hreflang attributes?

AnQiCMS as an efficient and flexible content management system provides a solid foundation for users in global content promotion, and its built-in multilingual support feature is the key to achieving this goal.Display language switch options correctly on your website and configure the `hreflang` attribute for search engines, which not only greatly enhances user experience but is also an important step for international SEO optimization.### One, Preparation: Enable AnQiCMS Multilingual Functionality AnQiCMS itself has strong multilingual support capabilities

2025-11-08

How to manage and display the homepage banner carousel?

The homepage banner carousel is the face of the website, which not only attracts the attention of visitors in the first place, but also an important carrier for conveying brand information and promoting core products or services.In AnQiCMS, managing and displaying the homepage banner carousel is a straightforward and flexible process, allowing you to easily create an eye-catching visual focus for your website. ### One, manage your Banner content in the background To manage the homepage Banner carousel, you first need to log in to the AnQiCMS backend management interface. Usually

2025-11-08