How to use if and for tags in templates to implement conditional judgment and loop display of data?

Calendar 👁️ 73

When building a website with AnQiCMS, the template is the key to content display.By flexibly using template tags, we can present the content of the background management in various forms. Among them,ifandforTags act as the core of template logic control, helping us to implement conditional judgments and the cyclic display of data, making the website content more dynamic and rich.

AnQiCMS's template engine borrows the syntax style of Django, which makes learning and using these tags very intuitive.It allows us to directly write logic in the template, display different content based on different conditions, or iterate through a dataset, outputting each data item one by one without complex programming knowledge.

I. Conditional judgment: Flexible control of content display (iftags)

ifTags are the basis for conditional judgment, allowing us to decide whether or not to display, or how to display a piece of content based on the truth or falsity of a condition. Its basic structure is very simple, through{% if 条件 %}and ends with{% endif %}end.

Basic usage

Imagine, you want to display the article title on the article detail page, but some articles may be empty due to some reason. You can useiftags to judge:

{% if archive.Title %}
    <h1>{{ archive.Title }}</h1>
{% else %}
    <h1>[无标题]</h1>
{% endif %}

This code will checkarchive.TitleDoes it exist, if it exists, display the article title, otherwise display '[No Title]'.

If-else conditions

When you need to handle more complex logic,ifTags also supportelif(else if) andelseTo build multiple judgments. For example, would you like to display different styles based on the article ID:

{% if archive.Id == 1 %}
    <p class="highlight-article">这是ID为1的特别文章。</p>
{% elif archive.Id > 100 %}
    <p class="new-article">这是一篇较新的文章,ID大于100。</p>
{% else %}
    <p>这是一篇普通文章。</p>
{% endif %}

Here, the template will first check if the article ID is 1, if not, then check if it is greater than 100, and finally, if neither condition is met, it will display a prompt for a regular article.

Example of practical scenarios

ifTags are widely used in practical applications. For example, determining whether a data set contains an image thumbnail to decide whether to display the image:

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

Or in the navigation menu, add different CSS classes based on whether the current page is active:

<li class="{% if item.IsCurrent %}active{% endif %}">
    <a href="{{ item.Link }}">{{ item.Title }}</a>
</li>

These all demonstrateifThe powerful role of tags in controlling the visibility and style of page elements.

II. Loop display: Efficiently present list data (fortags)

forThe tag is used to iterate over array or collection type data, displaying each item of the collection one by one.This is crucial in scenarios such as displaying article lists, product lists, and navigation menus.It's basic structure is{% for 变量名 in 集合 %}and ends with{% endfor %}end.

Basic usage

Assuming you get an article list from the AnQiCMS backend ({% archiveList archives with type="list" limit="10" %}This label is retrieved) and assigned toarchivesThis variable. You can display it like this in a loop:

{% 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 %}

here,articleThat is each data item in the loop, we can usearticle.Title/article.Linkand so on.stampToDateIs a date formatting function provided by AnQiCMS, which can convert timestamps into a readable date format.

Loop auxiliary variable

forWithin the loop, some very useful auxiliary variables are also provided to help us better control the loop logic or display information:

  • forloop.Counter: The current iteration number of the loop, starting from 1.
  • forloop.Revcounter: The number of times the current loop is away from the end, counting down from the total.

For example, do you want to add a 'new' tag to the first article in the list:?

{% for article in archives %}
    <div class="article-item {% if forloop.Counter == 1 %}latest-article{% endif %}">
        {% if forloop.Counter == 1 %}<span>[最新]</span>{% endif %}
        <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
        <p>这是第 {{ forloop.Counter }} 篇文章。</p>
    </div>
{% endfor %}

Handle empty data

If the collection in the loop may be empty, you would like to display a friendly prompt when there is no data instead of leaving it blank, you can use{% empty %}Sub-tag:

{% for article in archives %}
    <!-- 显示文章内容 -->
{% empty %}
    <p>抱歉,目前没有可显示的文章。</p>
{% endfor %}

WhenarchivesWhen the collection is empty,{% empty %}The content inside the block will be displayed.

Advanced usage: Sorting and Reversing

forTags also supportreversedandsortedA modifier used to reverse or sort the collection before the loop (for integer arrays).

{% for item in archives reversed %}
    <!-- 以相反的顺序显示文章 -->
{% endfor %}

{% for item in some_numbers sorted %}
    <!-- 对数字进行排序后显示 -->
{% endfor %}

III.ifwithforApplication of the combination.

ifandforThe true power of tags lies in their ability to be combined, creating highly dynamic and interactive template structures when used together.

Build multi-level navigation menus

A common example is to build a multi-level navigation menu. It is from AnQiCMS.navListThe tag can get navigation data, which may contain sub-navigation.NavList. We can use it toforTraverse the main navigation, and then useifDetermine if there is a child navigation, if so, use it againforTraverse the child navigation.

{% navList navs %}
<ul class="main-nav">
    {% for main_item in navs %}
        <li {% if main_item.IsCurrent %}class="active"{% endif %}>
            <a href="{{ main_item.Link }}">{{ main_item.Title }}</a>
            {% if main_item.NavList %} {# 判断是否有子导航 #}
                <ul class="sub-nav">
                    {% for sub_item in main_item.NavList %} {# 遍历子导航 #}
                        <li {% if sub_item.IsCurrent %}class="active"{% endif %}>
                            <a href="{{ sub_item.Link }}">{{ sub_item.Title }}</a>
                        </li>
                    {% endfor %}
                </ul>
            {% endif %}
        </li>
    {% endfor %}
</ul>
{% endnavList %}

This example perfectly demonstratesifandforHow to collaborate, dynamically generate complex user interfaces based on the hierarchical structure of data.

IV. Notes for writing templates.

While usingifandforWhen labeling, some details need to be paid attention to in order to ensure the correctness and fluency of the template:

  • Tag closure: ifTags must be prefixed with `{%

Related articles

How to configure pagination tags to provide user-friendly content list navigation?

In Anqi CMS, as the content on our website becomes richer and richer, how to efficiently organize and present this information so that visitors can easily find what they need among the vast amount of content has become a key issue.Excellent content list navigation, especially the pagination feature, not only enhances user experience, but is also an indispensable part of search engine optimization (SEO).The AnQi CMS provides powerful and flexible pagination tags, allowing you to easily configure user-friendly content list navigation.### The Foundation of Content List: Configure Content Retrieval Tag In Anqi CMS, all content lists, whether articles

2025-11-09

How to use友情链接 tags to display partner websites at the bottom of the website or other areas?

In website operation, the friendship link of cooperative websites is not only an important part of search engine optimization, but also an effective way to expand brand influence and promote mutual traffic redirection.Display these important cooperative partnerships prominently on the website, such as at the bottom or sidebar, which can effectively enhance user trust and the authority of the website.AnQiCMS (AnQiCMS) provides a convenient friend link management function and flexible tag calling method, allowing you to easily achieve this goal.### Overview of the friendship link backend management Before using the `linkList` tag

2025-11-09

How to safely and effectively display user comment lists and message forms in a template?

In modern website operations, user-generated content (UGC) is an important component for enhancing website activity and user stickiness.User comments and online message functions not only promote community interaction and provide valuable feedback, but also help enhance the richness of content and the activity of search engines.AnQiCMS as a content management system focusing on efficiency, security, and customization, provides us with powerful and flexible support to display these features safely and effectively in templates.Ensure that the comment list and message form are presented beautifully while兼顾 safety and functionality

2025-11-09

How to customize a template to achieve personalized display of single-page content (such as "About Us")?

In website operation, personalized display is crucial for shaping brand image and enhancing user experience.Especially single pages like "About Us" and "Contact Information", which carry the core information of the enterprise, can better convey the brand story and enhance the user's trust through customized design.AnQiCMS (AnQiCMS) provides a flexible way to achieve this goal, even for users with little technical background.### Understanding the Single Page Content Mechanism of Anqi CMS In Anqi CMS, single page content (such as "About Us")

2025-11-09

How to ensure that the date and time are displayed correctly on the front end using the timestamp formatting tag?

In website content operation, the correct display of date and time information is crucial, as it not only affects the user's reading experience but also directly relates to the timeliness and accuracy of the information.AnQiCMS (AnQiCMS) understands this point and provides a powerful and flexible timestamp formatting tag, allowing developers and operators to easily convert the original timestamp stored on the backend into a date and time format that is intuitive and easy to read for front-end users.Why do we need timestamp formatting?\n\nWe know that the data stored on the website backend, especially publishing time, update time, comment time, etc.

2025-11-09

How to reference external HTML fragments (such as headers, footers) in AnQiCMS templates to display modular content?

In website operations, maintaining the modularization and high reusability of content can not only significantly improve development efficiency, but also make the website more flexible during iterative updates.AnQiCMS (AnQiCMS) provides a straightforward and efficient solution with its powerful template engine to achieve this goal.This article will delve into how to make clever use of the Anqi CMS template mechanism, referencing external HTML fragments such as headers and footers, thus building a website that is easy to manage and has a clear structure. ### The Value of Modular Content: Why Reference External HTML Fragments?Imagine

2025-11-09

How to define and use macro functions to reuse display logic in AnQiCMS templates?

In the template development of Anqi CMS, we often encounter the need to reuse HTML code snippets or display logic.If you copy and paste every time, it not only increases the amount of code, reduces development efficiency, but also brings many inconveniences in later maintenance.To solve this problem, AnQi CMS template engine provides a powerful macro function (Macro) that helps us achieve the reuse of display logic, making the template code more concise and efficient.What is a template macro function?\n\nA macro function can be understood as a "custom function" in the template.

2025-11-09

How does the template inheritance feature help developers build a unified and easy-to-maintain page layout?

In AnQiCMS, building a unified and easy-to-maintain page layout is crucial for the long-term healthy operation of any website.As the face of a website, the visual consistency of a page directly affects user experience and brand image;The maintenance efficiency behind it determines the speed of content updates and feature iterations.AnQiCMS's powerful template inheritance feature is the core tool to solve this challenge.The core concept of template inheritance lies in **reusability and layering**.It allows us to create a basic "master" template that includes the common structure and elements of all web pages, such as headers and footers

2025-11-09