How to perform conditional judgment (if-else) and loop traversal (for) in AnQiCMS templates?

Calendar 👁️ 55

AnQiCMS (AnQiCMS) is an efficient and customizable content management system. Its template engine design philosophy is to simplify the complexity of content presentation, allowing website operators to focus on content organization and optimization.In the daily operation of websites, we often need to display content based on different conditions, or traverse list data for dynamic rendering.AnQi CMS provides intuitive and powerful template tags, among which the most basic and core is conditional judgment (if-else)and loop traversal(forTags. Mastering the use of these tags is the key to creating flexible and responsive web pages that meet user needs.

The template engine syntax of AnQi CMS is similar to Django and Blade, which allows operation personnel familiar with other mainstream template engines to quickly get started.By these tags, we can accurately control the display logic of content, ensuring that users get **information experience when visiting the website.

Flexible use of conditional judgment(if-else)

In website content display, conditional judgment is an indispensable part. Whether it is to display different content based on user permissions, to judge the existence of data to avoid page errors, or to adjust the page layout based on specific business logic,if-elseLabels can provide strong support.

The conditional judgment label in Anqi CMS starts with{% if 条件 %}starts with{% endif %}ends. Its basic form is to judge whether a condition is true, and if it is true, then executeifBlock content.

For example, when we want to display specific information based on the document ID:

{% if archive.Id == 10 %}
    这是文档ID为10的文档的专属内容。
{% endif %}

In addition to simpleifJudgment, we can also use{% elif 条件 %}and{% else %}To build more complex logic.elifAllow us to set multiple mutually exclusive conditions, andelseIt acts as the default handling when all conditions are not met.

A common scenario is to judge based on the size of numbers:

{% if simple.number < 42 %}
    这个数字小于42。
{% elif simple.number > 42 %}
    这个数字大于42。
{% else %}
    这个数字就是42。
{% endif %}

The condition expression supports various operators, including comparison operators (==equal,!=Not equal to,>Greater than,<Less than,>=Greater than or equal to,<=Less than or equal to),logical operators(andLogical AND,orLogical OR,notLogical NOT), and member test operator (inContain). For example, we can determine whether a variable is empty or whether it is in some set:

{% if !simple %}
    'simple'变量不存在或为空。
{% elif "Text" in complex.post %}
    'complex.post'中包含"Text"这个字符串。
{% endif %}

By these flexible combinations, we can create various refined content display rules to ensure that the website presents the expected effect in different states.

Efficiently implement loop traversal (for)

In website operation, we often need to display list data, such as article lists, product lists, navigation menus, or image groups, etc.forThe loop iteration tag is exactly designed to meet such needs, it allows us to iterate over array, slice (slice) and other collection types of data, and process each element.

forThe basic syntax of a loop is{% for item in collection %}, and ends with:{% endfor %}end.itemwhich is the temporary variable name for the current element in each iteration,collectionand this is the collection we want to iterate over.

For example, iterate over a list ofarchivesarticles and display their titles and links:

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

During the loop, sometimes we need to know the current number of iterations, or apply different styles at special positions (such as the first or last item). Anqi CMS provides built-inforloopA variable that contains some useful information:

  • forloop.Counter: The current loop iteration number, starting from 1.
  • forloop.Revcounter: The reverse loop iteration number, indicating the number of remaining items.

We can make use offorloop.CounterAdd numbering or special styles to list items:

{% for item in archives %}
    <li class="{% if forloop.Counter == 1 %}active{% endif %}">
        <span>第{{ forloop.Counter }}篇,剩余{{ forloop.Revcounter }}篇</span>
        <a href="{{ item.Link }}">{{ item.Title }}</a>
    </li>
{% endfor %}

To meet different data display requirements,forLoops also supportreversedandsortedModifiers.reversedYou can reverse the traversal order, whilesortedYou can sort the collection:

{# 倒序遍历 #}
{% for item in archives reversed %}
    ...
{% endfor %}

{# 排序后遍历 #}
{% for item in archives sorted %}
    ...
{% endfor %}

{# 倒序并排序遍历 #}
{% for item in archives reversed sorted %}
    ...
{% endfor %}

When we need to traverse a collection that may be empty, we use{% empty %}the tag can elegantly handle this situation, avoiding blank pages or errors:

{% for item in archives %}
    <li>
        <a href="{{ item.Link }}">{{ item.Title }}</a>
    </li>
{% empty %}
    <li>当前没有任何内容可以显示。</li>
{% endfor %}

Furthermore,cycleThe tag is also very useful in loops, it can alternate the output of predefined values with each iteration, and is often used to implement effects like alternating row colors.

{% for item in archives %}
    <li class="{% cycle 'even' 'odd' %}">
        {{ item.Title }}
    </li>
{% endfor %}

ByforThese features allow us to easily build clear, rich, and dynamically responsive list pages.

Summary and Practical Suggestions

Conditional statements and loop traversal are the most basic and important components of Anqi CMS template development.As a website operator, being proficient in them can not only help us better understand and modify existing templates, but also quickly implement customized content display when needed.

In actual operation, please pay attention to the strictness of template tag syntax, for example, all tags must appear in pairs. At the same time, to maintain the cleanliness and readability of the template code, it is recommended to organize conditions and nested loops in a reasonable way and to make use of{%- ... -%}This syntax is used to eliminate unnecessary blank lines, making the final rendered HTML code more compact.By constantly practicing and trying, you will be able to fully utilize the potential of the Anqi CMS template engine to provide users with an excellent website experience.


Frequently Asked Questions (FAQ)

Q1: How to determine if a variable is empty or does not exist in the Anqi CMS template?

A1: You can use{% if variable %}To determine if a variable exists and is not empty. IfvariableThe value isnil, an empty string, 0,falseor an empty set,ifAll conditions will be judged as false. If you want to explicitly determine that a variable does not exist, you can use{% if not variable %}. For example:{% if category.Title %}It will check if the category title exists and is not empty;{% if not archives %}Will judgearchiveswhether the list is empty.

Q2: How can I implement alternating row coloring or styles for list items in a loop?

A2: You can use{% cycle 'value1' 'value2' %}tags to implement alternating row coloring.cycleThe label will output its parameters in order during each loop. For example, to implement different colors for odd and even rows, you can use the<li>label:

{% for item in articles %}
    <li class="{% cycle 'bg-light' 'bg-dark' %}">
        {{ item.Title }}
    </li>
{% endfor %}

Q3:ifTags support complex condition expressions, such as checking if multiple conditions are met at the same time?

A3:ifTags support logical operatorsand(Logical AND),or(Logical OR) andnotLogical NOT, as well as parentheses to combine complex conditions. For example:

{% if user.IsLoggedIn and user.IsVip %}
    欢迎VIP会员!
{% elif user.IsLoggedIn and not user.IsVip %}
    普通会员你好,升级VIP享受更多特权!
{% else %}
    请先登录。
{% endif %}

This combination method allows you to precisely control the display logic of content based on the status of multiple variables.

Related articles

How to include common code snippets like header and footer in AnQiCMS templates?

As an experienced AnQiCMS website operator, I am well aware of the importance of website template efficiency and maintainability for daily work.A well-designed template structure that ensures consistency in the brand image of the website, improves user experience, and significantly reduces the cost of content updates and website maintenance.In AnQiCMS, reasonably introducing common code snippets, such as the website header and footer, is the key to achieving this goal.

2025-11-06

What kind of template engine syntax does AnQiCMS support and how easy is it to learn?

As an experienced CMS website operation personnel, I fully understand the importance of an efficient and easy-to-use content management system for our daily work.Among other things, the flexibility and learning curve of the template engine are directly related to the efficiency of content display and the customizability of the website.AnQiCMS on this point, has provided us with a very friendly solution. ### AnQiCMS Template Engine Syntax Parsing One of AnQiCMS's core strengths lies in the template engine syntax it adopts.

2025-11-06

What is the template file structure and naming convention of AnQiCMS?

As an experienced website operator who deeply understands the operation of AnQiCMS, I know that the foundation of content presentation lies in its flexible and standardized template system.A deep understanding of AnQiCMS template file structure and naming conventions is the key to efficient website content management, personalized display, and system stability.The detailed principles of AnQiCMS template design will be elaborated.AnQiCMS template system is designed to provide high customization and ease of use.The core lies in a clear directory structure and a set of Django-style template syntax

2025-11-06

What are the detailed steps for installing AnQiCMS with Docker on Baota panel?

As an experienced security CMS website operator, I know that a smooth deployment process is crucial for the quick launch and stable operation of the website.Our team loves AnQi CMS for its lightweight, efficient Go language and powerful SEO features.Deploying AnQi CMS by combining Baota panel and Docker technology has brought convenience and flexibility to a new level.The complete steps for installing Anqicms using Docker on the Baota panel are detailed for you: ### Important Preparations Before Deployment Before installing Anqicms officially

2025-11-06

How does AnQiCMS implement multi-level category nesting calls and document list display?

In the operation practice of AnQiCMS, flexible content organization and presentation is the key to attracting and retaining users.The nested call of multi-level classification and the dynamic display of document lists is the core embodiment of AnQiCMS giving operation personnel strong content management capabilities.By skillfully applying system template tags, we can not only build a clear website structure but also present content accurately according to the reader's needs.

2025-11-06

How to add documents and set recommended attributes, SEO titles, and scheduled publishing in AnQiCMS?

As a professional who deeply understands the operation of AnQiCMS, I know that efficient content publishing and fine SEO optimization are the key to the success of the website.AnQiCMS provides intuitive and powerful tools to help us easily manage website content.This article will provide a detailed explanation of how to add new documents in AnQiCMS, focusing on how to set recommended properties, SEO titles, and scheduled publishing features to ensure your content reaches the target audience accurately and achieves better search engine performance.

2025-11-06

How to manage document categories in AnQiCMS and how to set custom fields for categories?

As a website operator who deeply understands the operation of AnQiCMS, I know the importance of content organization and personalized display for attracting and retaining users.In AnQiCMS, the management of document categories and the setting of custom fields are the core links to achieve this goal.A well-structured classification can help users quickly find the information they need, and flexible custom fields make content display more in-depth and diverse. ### Document Classification Management: Build a Clear Content Architecture In AnQiCMS, document classification is the foundation of website content organization.

2025-11-06

How to perform batch keyword replacement operations for documents in AnQiCMS backend?

As a senior practitioner who is deeply engaged in CMS content operation for enterprise safety, I know how crucial it is to efficiently update and maintain content in daily website management.AnQi CMS is not only favored for its simple and efficient architecture, but also for its powerful feature set, becoming a powerful assistant for us to improve operational efficiency.Among them, the document batch keyword replacement function is particularly prominent, which can help us unify the correction of content, ensure the timeliness and accuracy of information, and greatly reduce the burden of manual editing.

2025-11-06