How to implement conditional judgment and loop traversal in the Anqi CMS template to control content display?

Calendar 👁️ 70

In Anqi CMS, the template is the core of website content presentation, it is not only responsible for the layout and style of the content, but also undertakes the important responsibility of displaying different contents according to different conditions and cyclically presenting data lists.To make your website content more dynamic and interactive, it is particularly important to have a deep understanding of how to implement conditional judgment and loop traversal in templates.The Anqi CMS template engine uses syntax similar to Django, which allows you to quickly get started and flexibly apply it if you are familiar with web development.

Understanding AnQiCMS template basics

In AnQiCMS template files, variable output is usually defined using double curly braces, such as{{变量名称}}When performing logical operations such as conditional judgment and loop control, tags enclosed in single curly braces and percent signs are used, for example{% 标签名称 参数 %}These logical tags always appear in pairs, requiring an opening tag and an ending tag to define their scope, such as{% if 条件 %} ... {% endif %}or{% for item in 列表 %} ... {% endfor %}. Using these tags is the first step in controlling the flexibility of content display.

Flexible content display: conditional judgmentifTag

Conditional judgment is an indispensable part of the template, allowing you to decide which content should be displayed, which should be hidden, or presented in a different way based on the specific state of the data.ifThe tag is the core of this function.

The most basic form of conditional judgment is.{% if 条件 %} ... {% endif %}For example, you may want to display a special prompt only when the ID of an article is equal to 10.

{% if archive.Id == 10 %}
    <p>这是ID为10的特别推荐文章!</p>
{% endif %}

Herearchive.IdIs the ID of the current document, you can replace it with any available variable or expression.

When you need to handle more complex logic, you can useelif(else if abbreviation) andelseTags, to build multi-branch conditional judgment structures. For example, display different popularity levels according to the number of views of the article:

{% if archive.Views > 1000 %}
    <p>🔥 超级热门文章!</p>
{% elif archive.Views > 500 %}
    <p>✨ 热门推荐!</p>
{% else %}
    <p>📖 最新发布!</p>
{% endif %}

This structure allows the display of content to be precisely controlled according to multiple levels of conditions.

In addition to numerical comparison,ifTags can be used to determine if a variable exists, whether it is true, or if a list is empty, among other scenarios. For example, to check a picture path variableitem.ThumbIs there, to avoid displaying an empty image tag:

{% if item.Thumb %}
    <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
{% else %}
    <img src="/static/images/default.jpg" alt="默认图片">
{% endif %}

You can also combine filters (filters) to make more detailed judgments, such as checking if a string variable contains a certain keyword, or checking if the pagination data is the current page, so that you can add links to the current pageactiveStyle:

{# 假设 pages.FirstPage 是一个分页对象,其 IsCurrent 属性表示是否为当前页 #}
<a class="{% if pages.FirstPage.IsCurrent %}active{% endif %}" href="{{pages.FirstPage.Link}}">首页</a>

By flexible applicationif/elif/elseAnd various expressions, you can design highly customized display logic for each part of the website.

Dynamic content presentation: loop traversalforTag

The loop traversal feature is a powerful tool for handling list-like data (such as article lists, product lists, category navigation, etc.)forThe tag allows you to iterate over each element in a collection and generate the corresponding HTML structure.

forThe basic syntax of tags is:{% for item in 集合 %} ... {% endfor %}. Here,集合It is usually an array or list, anditemIt represents a temporary variable for each element in the loop. For example, display a list of articles:

{% archiveList archives with type="list" limit="5" %}
    {% for item in archives %}
        <li>
            <a href="{{item.Link}}">
                <h5>{{item.Title}}</h5>
                <p>{{item.Description}}</p>
            </a>
        </li>
    {% endfor %}
{% endarchiveList %}

In this example,archiveListThe tag fetched the first 5 articles, thenforLoop througharchivesa set to generate a list item for each article.

When you need to handle the case where the collection may be empty,forTags provide a{% empty %}A clause that executes its internal content when the collection is empty, rather than displaying an empty list. This is very user-friendly:

{% archiveList archives with type="list" limit="5" %}
    {% for item in archives %}
        <li>
            {# 文章内容 #}
        </li>
    {% empty %}
        <p>目前还没有任何文章发布。</p>
    {% endfor %}
{% endarchiveList %}

forThe loop also provides some built-in auxiliary variables to make loop control more refined. For example,forloop.CounterYou can get the current loop index (starting from 1),forloop.RevcounterGet the reverse index of the current loop. This is very convenient when you need to add numbers or special styles to list items:

{% for item in archives %}
    <li class="{% if forloop.Counter == 1 %}first-item{% endif %}">
        <span>第 {{ forloop.Counter }} 篇:</span>
        <a href="{{item.Link}}">{{item.Title}}</a>
    </li>
{% endfor %}

In addition to basic traversal,forThe tag also supports some modifiers:

  • reversedUsed for traversing the set in reverse.{% for item in archives reversed %}
  • sortedUsual for default sorting of the set (the document mentions sorting by int, but actual performance may vary depending on the data type).{% for item in archives sorted %}
  • cycleImplement a loop to output a series of values, such as alternating row background colors.{% for item in archives %} <li class="{% cycle 'even' 'odd' %}">...</li> {% endfor %}

Nested loops as well.forOne of the powerful functions of the label. For example, when displaying multi-level classification structures in website navigation or product categories, you may need to show:

{% categoryList categories with moduleId="1" parentId="0" %} {# 获取一级分类 #}
    <ul>
        {% for item in categories %}
            <li>
                <a href="{{ item.Link }}">{{ item.Title }}</a>
                {% if item.HasChildren %} {# 判断是否有子分类 #}
                    {% categoryList subCategories with parentId=item.Id %} {# 获取当前一级分类下的子分类 #}
                        <ul>
                            {% for inner in subCategories %}
                                <li><a href="{{ inner.Link }}">{{ inner.Title }}</a></li>
                            {% endfor %}
                        </ul>
                    {% endcategoryList %}
                {% endif %}
            </li>
        {% endfor %}
    </ul>
{% endcategoryList %}

In this way, you can easily build dynamic content blocks with different depths and structures.

Optimization and debugging tips

During template development, some tips can help you improve efficiency and code quality:

  1. Template comments: Use.{# 这是单行注释 #}Perform single-line comments, or use{% comment %} 这是多行注释 {% endcomment %}To perform multi-line comments. This helps with the readability and maintainability of the code, and these comments will not appear in the final rendered HTML.
  2. Remove blank lines: The template engine may fail to render due to logic

Related articles

How to customize TDK (Title, Description, Keywords) in Anqi CMS to optimize the display of pages in search results?

In website operation, the display effect of the page in search results is crucial for attracting users and increasing traffic.Among them, TDK (Title, Description, Keywords) is the core element that search engines understand the content of the page and decide how to display the page.AnQiCMS (AnQiCMS) provides users with flexible and powerful TDK customization features, helping us refine page optimization, thereby achieving better performance in search results.

2025-11-09

How to independently configure and display the content of each site in the Anqi CMS multi-site environment?

In today's rapidly developing digital age, many businesses and individual operators may not have just one website, but need to manage multiple brand sites, product display pages, or niche field blogs.How to ensure that in such a multi-site environment, each site's content can be independently configured, flexibly displayed, and maintain efficient management, which is a great challenge facing the operators.AnQiCMS (AnQiCMS) takes advantage of its powerful multi-site management function, providing an elegant and practical solution for this.The AnQi CMS was designed from the outset to consider the needs of multi-site operations

2025-11-09

How can Anqi CMS prevent the malicious collection of content and add watermarks to images for display?

Today, with the increasing importance of digital content, protecting original content from malicious collection and misuse has become a challenge for many website operators.Especially images, as the core carrier of visual information, the copyright protection should also not be neglected.AnQi CMS understands these pain points, therefore, in the system design, it especially integrates powerful anti-collection interference codes and image watermark functions, building a solid protective wall for our digital assets.### A clever layout to prevent malicious scraping Malicious scrapers often use automated programs to bulk harvest website content for unauthorized copying and distribution

2025-11-09

How to customize the display logic and content sorting of the search result page of Anqi CMS?

Optimizing the website's search results page, making it not only present information accurately but also sort intelligently according to user preferences, is a key link to improving user experience and website efficiency.AnQi CMS provides a powerful and flexible template engine and a rich tag library, making it intuitive and efficient to customize the display logic and content sorting of search result pages.In Anqi CMS, the search results page is usually controlled by a specific template file, which is located by default in the directory of the current template theme under `search/index.html` (or in flat mode under `search`)

2025-11-09

How to use the `archiveDetail` tag in AnQi CMS to display custom field content of a document?

AnQi CMS has a flexible content model design that allows users to add various custom fields to documents according to their business needs.These custom fields greatly enrich the expression of the website content, whether it is to display product specifications, event details, or additional information of articles, it can be handled with ease.How can `archiveDetail` tag be cleverly used on the document detail page to display these valuable custom field contents?### Understanding the core function of the `archiveDetail` tag In the Anqi CMS template system

2025-11-09

How does AnQi CMS truncate long text content and add an ellipsis?

In website content operation, effectively displaying information while maintaining the page's cleanliness and the smoothness of user experience is a crucial link.Especially for long text content, how to truncate the display on the list page or overview section with an ellipsis is a common technique to improve the readability and aesthetics of the website.AnQiCMS (AnQiCMS) is a feature-rich management system that provides a flexible mechanism to meet this requirement at the template layer.

2025-11-09

How to correctly render Markdown content as HTML and display mathematical formulas or flowcharts in Anqi CMS?

In AnQi CMS, using Markdown format to write content not only improves editing efficiency, but also maintains the structuralization and readability of the content.When content involves complex mathematical formulas or a clear flowchart needs to be displayed, the strength of Markdown becomes evident.Our company provides good support for this, let's take a look at how to correctly render and display these advanced contents on the website.### Step 1: Enable Markdown Editor First, make sure that your CMS system has enabled the Markdown editor feature

2025-11-09

How to implement pagination functionality in Anqi CMS and customize the display style of page numbers?

In AnQi CMS, the pagination feature of website content is an indispensable part of improving user experience and optimizing site structure.Whether it is a list of blog articles, product display pages, or other dynamic content, reasonable pagination makes it easier for users to browse a large amount of information and also helps search engines better understand and extract website content.Today, let's delve deeper into how to implement pagination in AnQiCMS and customize the display style of page numbers according to your own needs. ### Why do we need pagination? Imagine that your website has hundreds or even thousands of wonderful articles.If there is no pagination

2025-11-09