How to use conditional judgment and loop structures to dynamically display content in AnQiCMS templates?

Calendar 👁️ 69

In AnQiCMS templates, dynamic content display is the core of building interactive and data-driven websites.By using conditional judgment and loop structures, you can flexibly present information based on different data states, or efficiently traverse datasets to generate lists, tables, and other content.AnQiCMS's template engine uses syntax similar to Django templates, making these operations intuitive and easy to learn.

Next, we will delve into how to effectively use these powerful tools in the AnQiCMS template.

1. Conditional judgment: flexible display of content

Conditional structures allow your template to decide whether to display certain content based on specific conditions, or which part of the content to display.This is very useful when handling different user states, the existence or absence of data, or specific page logic.

Passing the conditional judgment in AnQiCMS template{% if ... %}Implemented with tags. Its basic structure is similar to many programming languages, supportsif/elif(short for else if) andelseclauses.

Basic usage:{% if condition %}You can use it to check if a variable exists, is true, or meets certain conditions. For example, on the article detail page, we only display it if the article has a thumbnail:

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

Here, archive.ThumbIt will be evaluated as a boolean value, if there is a thumbnail path (non-empty string), the condition is true.

Operator in conditional judgment:You can combine multiple operators to build complex conditions:

  • Comparison operator:==(equals,)!=(not equal,)>(greater than,)<(less than,)>=(greater than or equal to,)<=(less than or equal to).
  • Logical operator:and(AND),or(OR),not(Not).
  • Member operator:in(Check if an element exists in a set).

For example, check if the article ID is 10:

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

Check if the current item in the loop is the first in the list:

{% if forloop.Counter == 1 %}
    <span class="first-item-badge">热门</span>
{% endif %}

Provide an alternative:{% if ... %}{% else %}When the condition is not met, you may need to display another segment of content. In this case, you can useelse:

{% if archive.Content %}
    <div class="article-content">{{ archive.Content|safe }}</div>
{% else %}
    <p>抱歉,该文章内容正在撰写中,请稍后再访问。</p>
{% endif %}

|safeThe filter is very important here, it tells the template engine not to escape HTML tags in the article content, thereby correctly rendering rich text.

Multiple condition judgment:{% if ... %}{% elif ... %}{% else %}If your logic needs to handle multiple cases, you can useelif:

{% if user.IsVip %}
    <p>欢迎VIP会员,您可查看所有内容。</p>
{% elif user.IsLoggedIn %}
    <p>欢迎普通会员,部分高级内容需要升级VIP。</p>
{% else %}
    <p>请登录以查看更多内容。</p>
{% endif %}

In the above example, we assume thatuserobjects and theirIsVipandIsLoggedInProperty.

II. Loop structure: bulk generation of content

The loop structure is the key to handling collection data (such as article lists, category lists, image lists).By using loops, you can avoid repeating similar code, making the template more concise and easier to maintain.

The loop structure in AnQiCMS template passes{% for ... in ... %}Tag implementation.

Basic usage:{% for item in collection %}Loop through a collection, and assign the current element toitemVariable.

For example, get the latest 10 articles and display their titles and links:

{% archiveList archives with type="list" limit="10" %}
    <ul>
        {% for article in archives %}
            <li><a href="{{ article.Link }}">{{ article.Title }}</a></li>
        {% endfor %}
    </ul>
{% endarchiveList %}

HerearchiveListIt is an AnQiCMS built-in document list tag, which will store the query results toarchivesvariables, forforCyclic use.

Handle an empty collection:{% for ... %}{% empty %}If the collection in the loop may be empty, you can useemptya clause to provide a friendly prompt:

{% archiveList archives with type="list" categoryId="1" limit="5" %}
    {% for item in archives %}
        <div class="news-item">
            <h4><a href="{{ item.Link }}">{{ item.Title }}</a></h4>
            <p>{{ item.Description|truncatechars:100 }}</p> {# 使用truncatechars过滤器截断描述 #}
        </div>
    {% empty %}
        <p>当前分类下暂无文章。</p>
    {% endfor %}
{% endarchiveList %}

special variables in the loop:forloopInforInside the loop, the template engine provides a special variable namedforloopwhich contains information about the current loop state and is very useful:

  • forloop.Counter: The index of the current iteration starting from 1 (1, 2, 3…).
  • forloop.Revcounter: The index of the current iteration starting from the reverse of the total number of sets (…3, 2, 1).

These variables can be used to add numbers, apply special styles to the first or last element, etc.

For example, add background color to even rows:

{% categoryList categories with moduleId="1" parentId="0" %}
    {% for cat in categories %}
        <li class="{% if forloop.Counter is divisibleby:2 %}even-row{% else %}odd-row{% endif %}">
            <a href="{{ cat.Link }}">{{ cat.Title }}</a>
        </li>
    {% endfor %}
{% endcategoryList %}

Hereis divisibleby:2Is a filter used to determine if a number is divisible by 2.

Loop modifier:reversedandsortedYou canforAdd after tagreversedorsortedKeyword to change the order of the loop:

  • {% for item in collection reversed %}: Traverse the collection in reverse order.
  • {% for item in collection sorted %}:Follow the default order (usually by ID or name) and iterate.

Repetition pattern:{% cycle ... %}When you need to alternate between different values or CSS classes in a loop,cyclethe tag is very convenient:

{% archiveList archives with type="list" limit="5" %}
    {% for article in archives %}
        <li class="{% cycle 'list-item-odd' 'list-item-even' %}">
            <a href="{{ article.Link }}">{{ article.Title }}</a>
        </li>
    {% endfor %}
{% endarchiveList %}

This will make each article's<li>tags alternate owninglist-item-oddandlist-item-evenClass.

3. Combined use: Building complex pages

Conditional judgments and loop structures are often used together to deal with more complex page logic and data display requirements.

Example: Navigation with submenusA common scenario is to build a multi-level navigation menu. Submenus are displayed only when the main menu item has a submenu:

`twig\n{% navList navs %}

<ul class="main-menu">
    {% for item in navs %}
        <li class="main-menu-item {% if item.IsCurrent %}active{% endif %}">
            <a href="{{ item.Link }}">{{ item.Title }}</a>
            {% if item.NavList %} {# 检查是否存在下级导航 #}
                <ul class="sub-menu">
                    {% for subItem in item.NavList %}
                        <li class="sub-menu-item {% if subItem.IsCurrent %}active{% endif %}">
                            <a href="{{ sub

Related articles

How to control the automatic compression and thumbnail display of AnQiCMS front-end images after uploading?

In the process of operating a website, the management and optimization of image content is a key factor in improving user experience, accelerating website loading speed, and even affecting search engine rankings.AnQiCMS fully considered these needs, providing a flexible image processing mechanism that allows us to easily control the automatic compression and thumbnail display of uploaded images on the front end.### Content Setting: The Core Hub of Image Processing To finely manage the images on the AnQiCMS website, we need to first go to the "Background Settings" menu and then click on the "Content Settings" option

2025-11-07

How to display the name and description of user groups in AnQiCMS template?

In AnQiCMS template, flexibly display user group names and introductions AnQiCMS, as an efficient content management system, provides great convenience for website operators with its "User Group Management and VIP System" function, which can easily achieve user classification, content permission control, and member value-added services. However, in actual operation, how to naturally present these carefully set user group information, such as their names and detailed introductions, in the website front-end template so that users can clearly understand their identity privileges or exclusive rights to various services is a problem that template developers and content operators often encounter.

2025-11-07

How to dynamically add a website name suffix to the page title to optimize SEO display?

In content operation, the page title is undoubtedly the first barrier to attracting the attention of search engines and users.A clear, keyword-rich, and brand-consistent title that not only improves user click-through rate but is also a key element of search engine optimization (SEO).AnQiCMS is an enterprise-level content management and SEO optimization system that provides a flexible and powerful mechanism, allowing you to easily add a website name suffix to the page title, thereby achieving a win-win situation for brand enhancement and SEO.### Unified Brand Image

2025-11-07

How to prevent malicious collection of content in AnQiCMS and affect the exclusivity of front-end content?

Original content is the core value of the website, it condenses our thoughts, time and energy.However, the content has been maliciously collected, plagiarized, and published on other platforms, not only diluting the exclusivity of our content, but also potentially affecting the SEO performance of the website and even damaging the brand image.As website operators, we all hope that our front-end content can maintain its original exclusivity. 幸运的是,AnQiCMS was designed with this pain point in mind from the very beginning, incorporating multiple powerful features to help us effectively prevent content from being maliciously scraped and protect our original value. ### 1. Core Defense

2025-11-07

How to display the table of contents (ContentTitles) in the front-end template?

In the daily operation of websites, especially when publishing long articles, adding a clear table of contents (or content navigation) is crucial for improving user experience.It can not only help visitors quickly understand the structure of the article, conveniently jump to the chapters of interest, but also optimize the page SEO performance to a certain extent.AnQiCMS provides a very practical feature that allows us to easily implement the directory display of article content in the front-end template.### Understanding how AnQiCMS generates article contents AnQiCMS while processing article content

2025-11-07

How to correctly display the `hreflang` tag in a multilingual site for search engine guidance?

In today's globalized digital age, multilingual support has become a basic requirement for websites to reach a wider audience.However, providing different language versions of content is not enough, we also need to ensure that search engines can correctly understand the relationships between these different versions, so that users can be directed to the content most suitable for their language and region.This is where the `hreflang` tag comes into play.For websites built using AnQiCMS, correctly configuring the `hreflang` tag is a key step in improving international SEO performance

2025-11-07

How to customize the overall display template of AnQi CMS?

AnQi CMS provides a flexible and powerful template customization mechanism, allowing you to create a unique website style according to your actual needs.No matter whether you want to adjust the overall layout or display personalized design for specific content, Anqi CMS can provide clear paths and rich tools to support your creativity.One of the core advantages of AnQi CMS is its template engine.It adopts syntax similar to Django and Blade, which allows those familiar with web development to get started quickly.This syntax is intuitive and easy to understand, outputting data through `{{variable}}`

2025-11-07

How to implement adaptive, code adaptation, and independent template display for PC and mobile terminals in AnQiCMS?

In the era when mobile internet dominates, whether a website can provide a consistent and high-quality experience across different devices is directly related to user retention and brand image.AnQiCMS fully understands the needs of users for multi-platform experience, and therefore integrated flexible and diverse template display modes from the beginning of system design, helping users easily cope with challenges of various terminals such as PC, mobile phone, and so on.AnQiCMS provides three core template display modes, namely: adaptive mode, code adaptation mode, and independent template mode for PC and mobile terminals.These three modes have their respective focuses

2025-11-07