How to use if/for tags in a template to control the conditional display and looping display of content?

Calendar 👁️ 58

When building and operating a website, the dynamic display and flexible management of content are the key to improving user experience and operational efficiency. AnQiCMS (AnQiCMS) understands this and therefore its template engine provides powerful and intuitive conditional judgment ("}if) And Looping (",for) Tags, allowing you to easily control the display logic and achieve highly customized page layouts.

The template syntax of AnQiCMS has borrowed the concise style of Django template engine, with a very low learning cost.By mastering these core tags, you will be able to present website content flexibly based on specific conditions, or display list data efficiently without writing complex backend code.Let's delve deeper together to understand how to use these tags in templates, bringing vitality to your website content.

Conditional display: MasterifFlexible use of tags

ifTags are a powerful tool for conditional judgments in templates. They allow you to decide whether to display a piece of content based on the truth or falsity of an expression, or to choose one from multiple possibilities to display.This is very useful in many scenarios, such as displaying images based on whether the article has a thumbnail or displaying different operation buttons based on user permissions.

The most basicifThe usage is to judge a condition:

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

The meaning of this code is that if the current document (archive) contains a thumbnail (Thumb) then display this image. Ifarchive.ThumbIf empty or false, the image part will not be rendered on the page.

When you need to handle multiple mutually exclusive conditions, you can useelif(else if) andelseTag, which is very similar to the logic of the programming languages we commonly use:

{% if archive.Views > 1000 %}
    <span class="hot-badge">热门</span>
{% elif archive.Views > 500 %}
    <span class="popular-badge">受欢迎</span>
{% else %}
    <span class="normal-badge">普通</span>
{% endif %}

Here, we will base the document's page views (archive.Views) To display different badges. If the view count exceeds 1000, display 'Hot';If between 501 and 1000, display 'popular';Otherwise, display "Normal".

ifLabels can be used not only to determine if a variable exists or the size of the value, but also to perform complex logical judgments with other operators, such as determining whether a variable is not equal to a certain value, or whether a set contains a certain element.

{# 检查分类是否有子分类,决定显示子分类列表还是直接显示文档 #}
{% if category.HasChildren %}
    <!-- 显示子分类导航 -->
    <ul class="sub-category-list">
        {% categoryList subCategories with parentId=category.Id %}
        {% for subCat in subCategories %}
            <li><a href="{{ subCat.Link }}">{{ subCat.Title }}</a></li>
        {% endfor %}
        {% endcategoryList %}
    </ul>
{% else %}
    <!-- 显示当前分类下的文章列表 -->
    <ul class="article-list">
        {% archiveList articles with categoryId=category.Id limit="10" %}
        {% for article in articles %}
            <li><a href="{{ article.Link }}">{{ article.Title }}</a></li>
        {% endfor %}
        {% endarchiveList %}
    </ul>
{% endif %}

In this example,if category.HasChildrenIt will check if the current category has any subcategories. If there are, it will display the subcategory list;If not, display the article list under the category. This conditional judgment greatly improves the reusability and dynamics of the template.

Loop through:驾驭forThe powerful function of the tag

When you need to display a series of repeated content, such as article lists, product lists, navigation menus, or image galleries,forTags are your best choice. It can iterate over each element of an array or collection and execute the same template code for each element.

forThe basic syntax of loops is very simple:

{% for item in archives %}
    <div class="article-item">
        <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
        <p>{{ item.Description }}</p>
    </div>
{% endfor %}

here,archivesIt is a collection of document lists,itemIt represents a document object from the collection in each iteration. Byitem.Linkanditem.TitleWe can easily access the link and title of each document.

In the loop, you can also access some special variables that provide information about the current loop state, such as:

  • forloop.Counter: The current loop iteration number, starting from 1.
  • forloop.Revcounter: The remaining number of elements in the current loop.

These variables are very useful when applying different styles to specific items in the list:

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

This code will add to the first item in the navigation list.activeClass, this is very convenient when highlighting the default selected item.

If your list may be empty and you want to display a friendly prompt when there is no content, you can useemptyTags:

{% for product in products %}
    <div class="product-card">
        <h4>{{ product.Title }}</h4>
        <img src="{{ product.Thumb }}" alt="{{ product.Title }}" />
    </div>
{% empty %}
    <p>抱歉,目前没有产品可供展示。</p>
{% endfor %}

WhenproductsWhen the collection is empty,emptyThe content will be rendered to avoid blank or error on the page.

Of Security CMSforTags also supportreversedandsortedModifiers that allow you to easily reverse iterate through the collection or sort by some rule (for numeric types).

{# 倒序显示文章列表 #}
{% for item in archives reversed %}
    <!-- ... 文章内容 ... -->
{% endfor %}

Combine usage: Make the template more intelligent and efficient

ifandforThe real strength of tags lies in their combined use. While iterating through data in a loop, conditional judgments can be made based on the specific attributes of each data item, enabling the implementation of very complex dynamic content display.

Let's look at a classic example: building a multi-level navigation menu. Suppose we have a list of top-level categories, each of which may contain subcategories.

<nav>
    <ul class="main-nav">
        {% navList mainNavItems with typeId=1 %} {# 假设 typeId=1 是主导航 #}
        {% for mainItem in mainNavItems %}
            <li {% if mainItem.NavList %}class="has-submenu"{% endif %}>
                <a href="{{ mainItem.Link }}">{{ mainItem.Title }}</a>
                {% if mainItem.NavList %} {# 如果有子导航列表 #}
                    <ul class="submenu">
                        {% for subItem in mainItem.NavList %}
                            <li><a href="{{ subItem.Link }}">{{ subItem.Title }}</a></li>
                        {% endfor %}
                    </ul>
                {% endif %}
            </li>
        {% endfor %}
        {% endnavList %}
    </ul>
</nav>

In this example, the outer layerforLoop through the main navigation items. Inside each loop, we useif mainItem.NavListto determine if the current navigation item has a sub-navigation. If it does, we nest another one.forLoop to render the sub-navigation list. This structure allows you to build

Related articles

How to apply AnQiCMS pagination feature to the pagination display of article lists or Tag document lists?

In website content management, whether it is to display a large number of articles, products, or documents under categories, an efficient and user-friendly pagination function is crucial.It not only allows users to easily browse a large amount of content, avoid the slow loading caused by long pages, but also helps search engines better crawl and index website information.AnQiCMS is well-versed in this, providing intuitive and powerful pagination functions in template tag design, making it effortless to implement pagination display in article lists or Tag document lists.Understanding how AnQiCMS implements pagination

2025-11-08

How to display the friend link list at the bottom of the AnQiCMS website?

In website operation, friendship links play an indispensable role.It is not only an effective way for websites to recommend and share traffic with each other, but also an important means to enhance the weight and visibility of websites in search engines.However, how to conveniently manage and display these links on a website is a practical problem faced by many website managers.AnQiCMS as a system focusing on enterprise-level content management and SEO optimization, provides an intuitive link function and a flexible template calling mechanism, making this process extremely simple.###

2025-11-08

How does AnQiCMS display the website message form and customize the form field display?

AnQi CMS: Flexible display and field customization of the website message form In website operation, the message form is an important bridge connecting users and the website.Whether it is to collect customer feedback, provide consulting services, or interact with users, a well-functioning and easy-to-use comment form is particularly important.AnQiCMS (AnQiCMS) is well-versed in this field, providing users with a powerful and flexible feedback form feature, which can be easily displayed on the website front-end and supports in-depth customization of form fields to meet various business needs.### One,

2025-11-08

How to display the Tag list of articles and detailed information of a single Tag as well as associated documents in AnQiCMS?

How to effectively organize and display content in a content management system is the key to improving user experience and search engine friendliness.AnQiCMS provides a powerful Tag feature, helping us to classify and display content more finely.This article will provide a detailed introduction on how to flexibly use tags in AnQiCMS, including displaying tag lists, viewing detailed information of individual tags, and listing documents associated with specific tags.The role of tags in AnQiCMS Tags are a flexible content organization method in AnQiCMS

2025-11-08

How to format a timestamp into a readable date and time format for display in AnQiCMS?

The website content is updated frequently, each article, product, or comment has its creation and update time point.However, these times are usually stored in the background in the form of a series of numbers, which is what we commonly call timestamps.It is not friendly to display these timestamps to visitors, we need to convert them into a clear date and time format.In AnQiCMS, formatting these timestamps into the date and time format we are accustomed to is actually very simple and intuitive.The system comes with a powerful template tag that can help us easily achieve this.###

2025-11-08

How to define temporary variables in templates to assist in content display logic?

When using AnQiCMS for website content management, the flexibility of the template is crucial for achieving diverse content display.At times, we need not only to output data directly, but also to perform some temporary processing, calculation, or judgment based on business logic, at which point defining temporary variables in the template becomes particularly useful.This not only makes the template code more tidy, but also avoids repeated retrieval or calculation of the same data, thereby improving rendering efficiency and maintainability.The template engine syntax of AnQi CMS is similar to Django template engine

2025-11-08

How to reference the common template code snippets (such as header and footer) in AnQiCMS to unify the display of the page?

It is crucial to maintain a unified page style in website content operation to enhance user experience and maintenance efficiency.Imagine if your website had hundreds or even thousands of pages, and each page's header, footer, or sidebar needed to be manually modified, that would be an enormous project.Fortunately, AnQiCMS provides a powerful and flexible template mechanism that can help you easily refer to and manage common code snippets, ensuring the consistency of the website display.AnQiCMS's template system borrows the syntax of the Django template engine, making it easy to use and powerful.it passes `

2025-11-08

How to use the template inheritance feature of AnQiCMS to build a consistent page skeleton and display local content?

During the process of website construction and operation, how to efficiently manage page layout, ensure consistency in visual style, and be able to flexibly adjust local content is a challenge faced by many operators.AnQiCMS provides a powerful template inheritance function, which can help us cleverly solve these problems, realize the structural management of website pages and the flexible display of content.Understand the core concept of template inheritance Imagine that template inheritance is like a blueprint or master template in architectural design.We first design a universal page skeleton, which includes the shared elements of all web pages

2025-11-08