How to use conditional judgment (if) and loop traversal (for) tags for data rendering in AnQiCMS templates?

Calendar 👁️ 60

As a senior AnQi CMS website operations personnel, I know that flexible content presentation is crucial for attracting and retaining users. The powerful template engine of AnQiCMS, especially its conditional judgment (if)and loop traversal(for) Tags are the core tools for dynamic content rendering. They allow websites to maintain consistency in content structure while being able to flexibly display information based on data states and business logic.

The foundation of dynamic content rendering: Understanding AnQiCMS template tags

AnQiCMS uses a syntax similar to Django's template engine, allowing developers and operators to present backend data on the frontend in a concise and intuitive manner. All control flow tags, such as conditional judgments and loops, are used{% 标签名 参数 %}The format is defined and requires corresponding end tags{% end标签名 %}to close. The output of variables is through double curly braces{{ 变量名 }}To implement. Deeply understanding the application of these tags is the key to building a highly interactive and functional AnQiCMS website.

Conditional judgment: usingifTag implementation of content intelligent display

ifThe tag is the most basic logical control structure in AnQiCMS templates, which allows us to decide whether to display page content based on specific conditions.This allows the template to present personalized content based on different data states, user permissions, or page context.

ifBasic structure of tags include{% if 条件 %}/{% elif 其他条件 %}and{% else %}. EachiforelifBlock must be{% endif %}Label ends.The condition can be the existence check of a variable, numerical comparison, string comparison, or boolean value judgment.For example, we can determine if a document exists, if a list is empty, if a certain value is greater than a specific value, or if a user's attribute is true.

In practical applications,ifThe use of tags is very extensive. Suppose we need to display different prompt information on the article detail page according to the document ID, or to display the dropdown menu only if the content has subcategories.

{# 检查文档ID是否为10,显示特定内容 #}
{% if archive.Id == 10 %}
    <p>这是ID为10的特别推荐文章!</p>
{% elif archive.Id > 5 %}
    <p>这是一篇较新的文章。</p>
{% else %}
    <p>这是一篇普通文章。</p>
{% endif %}

{# 判断列表是否为空 #}
{% if categories %}
    <p>这里有分类内容。</p>
{% else %}
    <p>暂无分类数据。</p>
{% endif %}

{# 判断某个属性是否存在或为真 #}
{% if item.HasChildren %}
    <p>该分类包含子分类。</p>
{% else %}
    <p>该分类没有子分类。</p>
{% endif %}

It is worth noting that when negating boolean values, you can usenotkeywords such as{% if not item.IsCurrent %}. Use them flexiblyiftags, which can make the page logic clearer and the user experience smoother.

Loop traversal: useforTag efficient rendering of list data

forThe tag is the key used in AnQiCMS templates for iterating over collections (such as arrays, lists, or slices).It allows us to traverse each element in the dataset and generate the corresponding HTML structure, greatly enhancing the reusability of templates and the dynamic nature of content.

forThe basic syntax of tags is:{% for item in collection %}of whichcollectionIs the dataset to be traversed,itemIs the variable representing the current element in each iteration. The loop also needs to be{% endfor %}Tag closed.

AnQiCMS'forTags also provide some practical auxiliary functions:

  • forloopobject: Within the loop, you can access the current loop's metadata, such asforloopthe object accessing the current loop's metadata, for exampleforloop.Counter(current iteration count, starting from 1),forloop.Revcounter(From the current iteration count in reverse order of the total number). This is very useful when adding specific styles or logic to loop items.
  • reversedandsortedModifier: Can beforadded directly after the tag.reversedReverse traverse the collection or addsortedTraverse after sorting in the default order (usually ID or name).
  • emptyblockIf:forThe collection being traversed in a loop is empty, you can use{% empty %}Define the content to be displayed when there is no data, to avoid the page from being blank or displaying errors.

Suppose we need to display a list of multiple articles on a category page, we can use it like this.forTags:

{# 遍历文档列表 archives #}
{% archiveList archives with type="page" limit="10" %}
    {% for article in archives %}
        <div class="article-item {% if forloop.Counter == 1 %}featured{% endif %}">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
            <p>{{ article.Description }}</p>
            <span>发布日期: {{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
            <span>浏览量: {{ article.Views }}</span>
        </div>
    {% empty %}
        <p>抱歉,当前分类下没有可用的文章。</p>
    {% endfor %}
{% endarchiveList %}

This example shows,forloop.CounterUsed to add a class to the first article item,featuredname,emptyblock is in,archivesFriendly prompts are provided when the list is empty.

ifwithforThe combination application: Building complex views

In practical web development,ifandforLabels are often not used independently, but are nested and closely coordinated to achieve more complex business logic and page layout. By placingifstatements inforInside the loop, we can make a separate conditional judgment for each item in the loop; otherwise, usingifstatements to control whether to execute aforloop can avoid unnecessary rendering.

A common combination scenario is to display multi-level categories in the navigation menu. We can determine whether a first-level category contains subcategories while traversing it, and if it does, we can nest another one inside.forLoop to traverse and display second-level categories.

{# 遍历顶级分类,例如产品分类 #}
{% categoryList mainCategories with moduleId="2" parentId="0" %}
    <ul class="main-nav">
        {% for category in mainCategories %}
            <li {% if category.IsCurrent %}class="active"{% endif %}>
                <a href="{{ category.Link }}">{{ category.Title }}</a>
                {# 判断当前分类是否有子分类 #}
                {% if category.HasChildren %}
                    <ul class="sub-nav">
                        {# 遍历子分类 #}
                        {% categoryList subCategories with parentId=category.Id %}
                            {% for subCategory in subCategories %}
                                <li {% if subCategory.IsCurrent %}class="active"{% endif %}>
                                    <a href="{{ subCategory.Link }}">{{ subCategory.Title }}</a>
                                </li>
                            {% endfor %}
                        {% endcategoryList %}
                    </ul>
                {% endif %}
            </li>
        {% empty %}
            <li>暂无可用分类。</li>
        {% endfor %}
    </ul>
{% endcategoryList %}

In the example of the above navigation menu,{% if category.HasChildren %}Controls whether the submenu is rendered,<ul>structure, while the internal{% for subCategory in subCategories %}It is responsible for traversing and displaying specific sub-category items. This nested usage allows the template to handle complex data structures while maintaining clear and maintainable code.

Optimization and **practice** of template rendering

While usingifandforWhen tags render data, there are still some **practices** that can help us write more efficient and cleaner templates:

  • Use|safeFilterWhen the output content may contain HTML tags (such asarchive.Content), in order to avoid the browser automatically escaping and causing the tags to not be parsed, it should use|safeFilter, for example{{ article.Content|safe }}.
  • control spacing.:ifandforThe tag may introduce additional blank lines during rendering. To generate more compact HTML output, you can use a hyphen at the beginning or end of the tag.-For example{%- if condition %}or{% endfor -%}This will remove all whitespace on the corresponding side of the tag.
  • Variable definition and scope:{% with %}and{% set %}Tags allow temporary variables to be defined in templates. Although it is not direct.iforforBut they can help us store intermediate results, simplify complex conditional judgment or loop logic, especially inincludewhen passing specific variables in the template introduced,withthe tag is particularly applicable.
  • Multi-site compatibility: AnQiCMS supports multi-site management. When calling data tags, if you need to obtain data for a specific site, you can explicitly addsiteIdparameters, for example{% archiveList archives with siteId="2" %}.

By proficiencyifandforThese core template tags, combined with the other rich tags and practices provided by AnQiCMS, will enable you to build high-quality websites that are powerful, responsive, and easy to manage.


Frequently Asked Questions (FAQ)

1.forHow to judge whether the current item in a loop is the first or last item, and perform special processing?

You can useforloopto judge.forloop.CounterRepresents the current iteration count (starting from 1),forloop.LastIt is a boolean value indicating whether the current item is the last in the loop.

For example:

{% for item in archives %}
    <li {% if forloop.First %}class="first-item"{% endif %}
        {% if forloop.Last %}class="last-item"{% endif %}>
        {{ item.Title }}
    </li>
{% endfor %}

2. Why does myiforforalways appear extra blank lines around the tag? How can I eliminate them?

This is caused by the template engine retaining the white space around the control flow tags by default. To eliminate these extra blank lines, you can use a hyphen at the beginning or end of the tag.-Control spacing.

For example:

{# 消除 if 标签两侧的空行 #}
{%- if condition -%}
    <p>内容</p>
{%- endif -%}

{# 消除 for 标签每行末尾的空行 #}
{% for item in list -%}
    {{ item.Title }}
{%- endfor %}

3. How can Iforuse labels insideiftags to display different content or styles based on each loop item's properties?

You can directly useifNested in a tagforWithin a loop, for eachitemPerform conditional judgment.

For example, when displaying a list of articles, display different icons according to theFlagproperties (such as “recommended”) of the articles:

{% archiveList archives with type="list" limit="5" showFlag=true %}
    {% for article in archives %}
        <div>
            {% if "c" in article.Flag %} {# 假设 'c' 代表推荐 #}
                <span class="recommend-icon">★</span>
            {% endif %}
            <a href="{{ article.Link }}">{{ article.Title }}</a>
        </div>
    {% endfor %}
{% endarchiveList %}

Related articles

How to get the previous, next article and related documents with AnQiCMS template tags?

As a senior CMS website operation personnel in the security industry, I fully understand the importance of content in attracting and retaining users.Efficient content management and elegant user experience are the foundation of a successful website.In AnQiCMS, the flexible template tag system is the key to achieving this goal.Today, I will give you a detailed introduction on how to use AnQiCMS template tags to cleverly obtain the previous and next articles and related documents, thus optimizing your content layout, improving user experience and the website's SEO performance.### Optimize User Navigation: Get Previous Document On Article Detail Page

2025-11-06

How to obtain the current page's TDK information in AnQiCMS template and perform SEO optimization?

As an experienced website operator who deeply understands the operation of AnQiCMS, I have a very good understanding of the core value of TDK (Title, Description, Keywords) information for website search engine optimization (SEO).High-quality TDK is not only the key for search engines to understand the content of the page, but also the foundation for attracting users to click, improving website traffic and conversion rates.AnQiCMS as an enterprise-level content management system took full consideration of SEO requirements from the very beginning, providing a powerful and flexible TDK management and template calling mechanism.###

2025-11-06

How to implement flexible calls for document lists, category lists, and single page details with AnQiCMS template tags?

As a website operator who is deeply familiar with the operation of AnQiCMS, I know that content is the cornerstone of the website, and flexible and efficient content calls are the key to improving user experience and optimizing operational efficiency.AnQiCMS's powerful template tag system is the core tool we use to achieve this goal.It allows us to precisely control the display of document lists, category lists, and single-page details, thereby building website pages that are both beautiful and functional.

2025-11-06

How to use AnQiCMS template tags to get the system configuration information of the website (such as website name, Logo)?

As an experienced AnQi CMS website operation personnel, I am well aware of the importance of being able to flexibly call system configuration information when building and maintaining a high-efficiency, beautiful website.This information, such as the website name, logo, filing number, etc., is an indispensable part of the website's brand identity and basic operation.Strong and intuitive template tags provided by AnQi CMS allow you to easily obtain and display these system-level configuration information in website templates.

2025-11-06

How to implement quick multilingual switching of template content with translation tags in AnQiCMS?

As a senior AnQiCMS website operations personnel, I am well aware of the core status of content in website operations, especially under the wave of globalization, the rapid switching of multilingual content is crucial for user experience and market expansion.AnQiCMS provides a powerful and concise multilingual support mechanism, with its core being the flexible use of translation tags `{% tr %}` to quickly switch the multilingual content of templates.

2025-11-06

How to enhance the display of structured data on the page with AnQiCMS's Json-LD custom call tag?

As an experienced CMS website operation person in the digital world, I know the power of content.High-quality content is the foundation for attracting and retaining users, and how to make these contents better understood and displayed by search engines is one of the core issues for our operation staff.Today, I want to delve deeply into the Anqi CMS Json-LD custom call tag, and how it has become a powerful tool for us to enhance the display of structured data on web pages.

2025-11-06

What specific SEO elements does the "Home TDK" in AnQiCMS refer to?

As an experienced website operator, I know that Search Engine Optimization (SEO) is the key to the success of a website, and the setting of the TDK (Title, Description, Keywords) on the homepage is the foundation for our SEO work.AnQiCMS is a system focused on efficient content management, which fully considers SEO requirements from the beginning of its design, providing us with a simple and powerful TDK configuration function.I will elaborate in detail on the specific SEO elements and their operational significance referred to by the home page TDK in AnQiCMS

2025-11-06

How to find and enter the 'Home TDK Settings' area in the AnQiCMS backend?

In the AnQiCMS backend management, finding and entering the "Homepage TDK Settings" area is a key step for website operators to perform basic SEO optimization.These settings directly affect the display effect of the homepage in search engine results and are an important factor in attracting potential users to visit.As an experienced website operator proficient in AnQiCMS, I will guide you through this operation effortlessly.First, make sure you have successfully installed and run the AnQiCMS website and have the login credentials for the administrator account.To access the AnQiCMS admin interface

2025-11-06