How to write conditional judgment (if/else) and loop (for) logic tags in AnQiCMS templates?

Calendar 👁️ 56

As a professional who deeply understands the operation of AnQiCMS, I know that template design plays a core role in the presentation of website content.By flexibly using conditional judgment and loop logic, we can transform static template files into dynamic and intelligent content display platforms, thereby better responding to user needs and improving the interactivity and user experience of the website.This article will discuss in detail how to write conditional judgment in AnQiCMS templates (if/else)and loop(for)Logical tag, helping you create a more expressive website.

Build dynamic content in AnQiCMS templates: conditional judgment and loop logic

AnQiCMS's template engine syntax is similar to Django, which provides a friendly learning curve for developers familiar with the Python ecosystem. In the template, variables are enclosed in double curly braces{{变量}}Define, while logical tags such as conditional judgment, loop control, etc. use single curly braces and percent signs{% 标签 %}to declare. Understanding and skillfully using these logical tags is the key to realizing dynamic content rendering.

Flexible conditional judgment:if/elseThe application of tags

In website operation, we often need to decide based on specific conditions whether to display a certain content block, use a certain style, or display different text information. AnQiCMS'if/elseLogical labels provide strong support for these scenarios.

BasicifThe statement is used to determine if an expression is true. If the condition is true, then execute.{% if %}and{% endif %}For example, when we need to determine whether the current document ID is a specific value, we can write it like this:

{% if archive.Id == 10 %}
    <p>这是文档ID为10的文档的特殊内容。</p>
{% endif %}

In practical applications, conditions are often not just one, or need to handle multiple possibilities. At this point, we can introduceelif(else if abbreviation) andelse.elifallows us to set multiple alternative conditions, andelseIt acts as the default handling when all conditions are not met.

For example, display different information based on the user's login status or content review status:

{% if user.IsLoggedIn %}
    <p>欢迎回来,{{ user.UserName }}!</p>
{% elif archive.Status == 0 %}
    <p>该内容正在审核中,请耐心等待。</p>
{% else %}
    <p>请登录以查看更多信息。</p>
{% endif %}

The condition expression supports various operators, including comparison operators (==,!=,<,>,<=,>=)、logical operators(and,or,not)and member operators(inThis means you can build very complex logic to control the display of content. For example, you can check if a value is in a certain set:

{% if category.Id in [1, 5, 8] %}
    <p>这个分类属于特色分类。</p>
{% endif %}
{% if not archive.Thumb %}
    <p>该文档没有缩略图。</p>
{% endif %}

Please note that alliftags must be with{% endif %}end, whileelifandelseTags do not require separate closing tags. When writing conditional judgments, it is crucial to maintain paired tags and correct nesting to avoid template rendering errors.

Powerful data traversal:forThe use of loop tags:

A content management system is characterized by the presentation of batch content, such as article lists, product lists, and category navigation, etc. AnQiCMS'sforThe loop label is designed for this kind of scenario, it allows us to traverse array, slice and other collection types of data, and process each element.

The most basicforThe loop structure is as follows, it will traversearchivesEach one in the collectionitem:

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

Inside the loop, we can access various properties of the current element using dot notation (item.属性名) and AnQiCMS provides many built-in tags (such asarchiveList,categoryList,navListto get the list data, these tags usually return data that is available forforcycling through the collection.

to provide more control and information within the loop,forThe loop also provides some special variables:

  • forloop.Counter: represents the current loop index, starting from 1.
  • forloop.Revcounter: represents the reverse index of the current loop, starting from the length of the collection in reverse order.

For example, add a special style class to the first item in the list:

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

When dealing with list data, we may also need to control the order of the data.forLoop supportreversedandsortedmodifier:

  • reversedTraverse the collection in reverse order.
  • sortedTraverse the sorted collection.
{# 倒序遍历 #}
{% for item in archives reversed %}
    <li>{{ item.Title }}</li>
{% endfor %}

{# 排序后遍历 #}
{% for item in archives sorted %}
    <li>{{ item.Title }}</li>
{% endfor %}

Sometimes, when the collection is empty, we want to display a prompt message instead of an empty list.forprovided a loopemptyBlock to handle this situation:

{% for item in archives %}
    <li>{{ item.Title }}</li>
{% empty %}
    <li>目前还没有相关内容。</li>
{% endfor %}

Furthermore,cycleThe tag is inforIt is also very useful in loops, allowing you to output a series of values in order at each iteration. This is often used to add alternating background colors or CSS classes to list items:

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

Points to note in practice

When writing AnQiCMS templates, whether usingif/elseOrforloops, it should be remembered that the AnQiCMS template syntax is strictly case-sensitive. Variable names (such asarchive.Id,item.Title) and tag names (such asif,for,endfor) must match the definition in the document. Any minor spelling or case errors can cause template parsing to fail or display abnormalities.

To maintain the cleanliness and maintainability of the template code, it is crucial to reasonably nest conditional judgments and loop structures. At the same time, if the line breaks or white spaces generated by the logic tags in the template affect the layout of the final page, you can use a hyphen.-Remove leading and trailing whitespace from tags, for example{%- if condition %}or{{ variable -}}.

By mastering these conditional judgment and loop logic tags, you will be able to fully utilize the powerful functions of AnQiCMS to build a highly dynamic, user-responsive, easy-to-manage, and optimized website.


Frequently Asked Questions

AnQiCMS template inifDoes the tag support complex logical conditions?Yes, the AnQiCMS template supportsifThe tag supports complex logical conditions. You can combine comparison operators (==,!=,<,>,<=,>=)、logical operators(and,or,not)and member operators(inTo construct multiple judgments. For example, you can check{% if item.Status == 1 and item.Views > 100 %}To filter items that meet two conditions.

InforHow to get the current loop index in a loop (for example, to determine if it is the first item or the last item)?in AnQiCMS'sforthe loop, you can useforloop.CounterTo get the current loop index (starting from 1), or useforloop.RevcounterTo get the reverse index. This is very useful for adding specific styles or logic to list items, for example{% if forloop.Counter == 1 %}To determine if it is the first item.

If my list data may be empty,forHow to elegantly handle this situation in a loop?When yourforIf the collection being traversed by the loop may be empty, you can use{% empty %}tag to provide an alternative content block. If the collection does not contain any elements,{% for %}The content inside the tags will not be rendered, instead{% empty %}and{% endfor %}the content between them, which allows you to elegantly display a “no content” prompt to the user.

Related articles

How to properly define and use variables in the AnQiCMS template?

As an experienced security CMS website operation person, I know that high-quality and clear content is the key to attracting and retaining users.In AnQiCMS template development, correctly defining and using variables is the foundation for dynamic content display and improving user experience.Below, I will elaborate on how to define and use variables in AnQiCMS templates, to help you better master content display.

2025-11-06

How should static resources (CSS/JS/images) be stored and referenced in the AnQiCMS template?

As a website manager who is deeply familiar with AnQiCMS operation, I know that proper management of website static resources is crucial for improving user experience and website performance.In AnQiCMS template development and maintenance, reasonably storing and referencing CSS, JavaScript, and images, etc., is the foundation for building an efficient and stable website.Below, I will elaborate on this key link.

2025-11-06

What file extension should AnQiCMS template files use?

As an experienced AnQi CMS website operation personnel, I know that template files play a core role in building a flexible and efficient website.They not only carry the visual presentation of the website, but also serve as a bridge for content and user interaction.For Anqi CMS, understanding the composition and usage specifications of its template files is the foundation for efficient content management and website optimization.According to the official document of Anqi CMS, template files uniformly use the file extension `.html`.

2025-11-06

How to use built-in filters (such as `truncatechars`, `upper`) to process and convert the data format of template variables?

As an experienced AnQiCMS website operation person, I am fully aware of the importance of content in attracting and retaining users.High-quality content not only requires careful creation, but also needs to be presented in an appropriate format and optimized to enhance user experience and readability.AnQi CMS, with its flexible Django template engine syntax, provides us with powerful built-in filter functions, allowing us to easily process and convert the data format of template variables.Next, I will give a detailed introduction on how to use the built-in filter of Anqi CMS

2025-11-06

What character encoding format should the AnQiCMS template file follow when editing?

As an experienced website operator who deeply understands the operation of AnQiCMS, I know that the details of content presentation are crucial to user experience.The character encoding of the template file is one of the essential basic links that should not be ignored.Clear and accurately displaying content is the first step to attracting and retaining users. ### AnQiCMS Template File Character Encoding Specification AnQiCMS template files must strictly follow the UTF-8 character encoding format when edited and saved.

2025-11-06

How to create a responsive, code adaptation, or PC+mobile separation template for the AnQiCMS website?

As a website content expert who deeply understands the operation of AnQiCMS, I know that a high-quality template is crucial for the attractiveness and user retention of the website.AnQiCMS provides great flexibility in template design, supporting various modes to meet different business needs and user access habits.Next, I will elaborate on how to create adaptive, code adaptation, or PC + mobile terminal separation templates for the AnQiCMS website.

2025-11-06

How to set up an independent directory structure for the mobile template of AnQiCMS?

As a website operator who is deeply familiar with the operation of AnQiCMS, I know that a flexible and efficient template management mechanism is important for the website, especially in the mobile-first era, providing an independent optimized template experience for mobile devices is the key to attracting and retaining users.AnQiCMS provides powerful support in template design, including setting up a separate directory structure for mobile templates, which allows us to provide customized content display and interactive experience for different devices.

2025-11-06

Where is the root directory of AnQiCMS template located?

As a senior security CMS website operator, I fully understand the core position of templates in website construction and content presentation.The template not only determines the visual style of the website, but also directly affects user experience and the efficiency of content delivery.Accurately understand the storage location of the template file is the basis for carrying out any website customization and optimization work. ### The Root Directory Location of AnqiCMS Templates In the architecture design of AnqiCMS, all the core files of the website templates are stored in a clear root directory.

2025-11-06