How to control the conditional display and loop display of AnQiCMS page content with Django template syntax?

Calendar 👁️ 65

In the flexible and powerful AnQiCMS content management system, the dynamic display of page content cannot do without the support of template syntax.Mastering conditional display and looping presentation, these two core functions can help us present data more efficiently and accurately on the website front-end.AnQiCMS uses a template syntax similar to Django, which makes the creation of content templates both familiar and easy to use.

Basic Template Syntax: The Foundation for Building Dynamic Pages

In AnQiCMS templates, we mainly use two tags to handle dynamic content:

  • Variable output{{ 变量 }}Used to display data directly on the page, for example{{ siteName }}It will output the website name.
  • Logical label{% 标签 %}Used to control the logic flow of the page, such as conditional judgments, loop iterations, etc. These tags usually require a corresponding end tag, such as{% if 条件 %}...{% endif %}.

Additionally, there areFilter|Used to format or process variables, making data more beautiful and meet the needs.

Conditional display: Decide the content to keep or discard based on specific conditions.

Conditional display is an indispensable part of template design, allowing us to flexibly display or hide specific content blocks on the page based on different data states. It is in the AnQiCMS template.ifThe label provides strong support for this.

Useif/elif/elseMake a conditional judgment.

ifThe basic usage of tags is similar to most programming languages, which can be used to determine if a variable exists or meets a specific value or range.

For example, we may want to display the image only when the article has a thumbnail:

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

here,archive.ThumbIf there is a value (not empty), the thumbnail of the article will be displayed; otherwise, a preset default image will be displayed.

In more complex scenarios, we can combineelif(else if abbreviation) andelseto handle multiple conditions:

{% if archive.Views > 1000 %}
    <p>这是一篇非常受欢迎的文章!</p>
{% elif archive.Views > 500 %}
    <p>这篇文章有不错的阅读量。</p>
{% else %}
    <p>欢迎阅读这篇文章。</p>
{% endif %}

In addition to directly comparing values,iflabels also support usingand/or/notlogical operators to combine conditions, as well asinoperators to determine whether an element is in a list:

{% if archive.Flag and archive.CreatedTime > currentTime %}
    <p>这篇文章被标记且是定时发布的。</p>
{% endif %}

{% if category.Id == 1 or category.Id == 5 %}
    <p>这是一个特殊分类。</p>
{% endif %}

{% if not user.IsLoggedIn %}
    <p>请先登录。</p>
{% endif %}

By these flexible condition judgments, we can provide customized page experiences for different users and different content states.

Loop display: Batch display dynamic data.

When we need to display a set of data, such as an article list, product list, or navigation menu, the repeated display becomes particularly important. In the AnQiCMS template,forTags are the tools to achieve this function.

UseforTags traverse the data set.

forThe tag is used to traverse arrays, lists, or any iterable objects. Each iteration, it assigns the current iterated element to a temporary variable for use within the loop body.

For example, show a list of articles:

{% archiveList archives with type="list" categoryId="1" limit="10" %}
    <ul>
        {% for item in archives %}
            <li>
                <a href="{{ item.Link }}">{{ item.Title }}</a>
                <span>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
            </li>
        {% empty %}
            <li>抱歉,目前没有找到相关文章。</li>
        {% endfor %}
    </ul>
{% endarchiveList %}

In this example:

  • {% archiveList archives with type="list" categoryId="1" limit="10" %}Is an AnQiCMS provided content tag, it retrieves the most recent 10 articles from the category with ID 1 and stores the results inarchivesthe variable.
  • {% for item in archives %}Start the loop, assign each loop toarchivesone article objectitem.
  • In the loop body, we can{{ item.Link }}access the article link,{{ item.Title }}access the article title,{{ item.CreatedTime }}Access creation time.
  • {% empty %}IsforA supplement to the tag whenarchivesWhen the list is empty,emptyThe content within the block will be displayed, which is very useful for friendly user prompts.
  • {% endfor %}Signifies the end of the loop.

forLoops have auxiliary variables and advanced usage

InforInside the loop, AnQiCMS provides some special auxiliary variables to make our loop control more precise:

  • forloop.CounterThe current iteration number (starting from 1).
  • forloop.RevcounterThe remaining iteration number of the loop.

Using these variables, we can implement specific styles or logic:

{% categoryList categories with moduleId="1" parentId="0" %}
    <nav>
        {% for item in categories %}
            <a href="{{ item.Link }}" {% if forloop.Counter == 1 %}class="first-item"{% endif %}>
                {{ item.Title }} ({{ forloop.Revcounter }} more)
            </a>
            {% if item.HasChildren %}
                {# 嵌套循环显示子分类 #}
                <ul>
                    {% categoryList subCategories with parentId=item.Id %}
                        {% for subItem in subCategories %}
                            <li><a href="{{ subItem.Link }}">{{ subItem.Title }}</a></li>
                        {% endfor %}
                    {% endcategoryList %}
                </ul>
            {% endif %}
        {% endfor %}
    </nav>
{% endcategoryList %}

This demonstrates how to add a class to the first element of a listfirst-itemand how to build multi-level category navigation through nestingcategoryListTags andforusing loops.

forTags also supportreversedandsortedA keyword used to reverse the iteration order or sort a list (if the list elements are sortable), which is very useful when a different display order is needed.

Apply to actual: Using AnQiCMS common content tags

AnQiCMS provides a wealth of built-in content tags, and the data structures they return are mostly directly applicable toifandforUse tags together.

  • Document list (archiveList): Used to get a list of articles or products. BymoduleIdspecifying the model,categoryIdspecifying the category,limitControl quantity

Related articles

How do AnQiCMS template file suffix and directory structure affect the display of front-end pages?

During the process of building a website with AnQiCMS, the template file suffix and directory structure play a crucial role, as they directly determine how the content of your website is presented to visitors.Understanding these rules can help us customize the appearance of the website more efficiently and achieve personalized content display.First, AnQiCMS uses the `.html` extension as the unified suffix for template files.This means that all template files we edit and create will end with .html.This convention not only makes the file type clear at a glance

2025-11-08

How can the scheduled publishing function ensure that content is displayed and launched accurately at the specified time?

## SecureCMS Scheduled Publishing Feature: The Secret to Accurately Going Live at the Specified Time In today's fast-paced digital content world, efficiently and accurately publishing content is one of the keys to the success of website operations.Whether it is press releases, new product launches, limited-time promotions, or regular updates of series articles, manual operation is not only time-consuming and labor-intensive, but may also lead to content not being online on time due to human error.At this time, a reliable scheduled publishing function is particularly important.AnQiCMS (AnQiCMS) knows this user's need

2025-11-08

How to set up and display exclusive content for VIP users or membership services?

In content operation, introducing VIP exclusive content or membership services to the website is an effective way to enhance user stickiness and achieve content monetization.AnQiCMS (AnQiCMS) fully understands the importance of this need, therefore it has built a complete user group management and VIP system, allowing you to easily build and manage such services. **Core: User Group Management and VIP System** One of the core strengths of AnQi CMS lies in its flexible user group management and VIP system.This means you can create user groups of different levels according to your business needs, and set unique permissions for each user group

2025-11-08

What is the impact of AnQiCMS anti-crawling function on the display of picture watermarks and content?

In today's internet age, where content is exploding, the value of original content is becoming increasingly prominent, but the issues of content theft and scraping that come with it also make many website operators headaches.AnQiCMS (AnQiCMS) fully understands this, and therefore integrates powerful anti-crawling and watermark management functions into the system design, aiming to effectively protect the original content and image copyrights of our website.How do these features specifically affect the display of picture watermarks and content on our website?Let us explore further. ### Image Watermark

2025-11-08

How to ensure UTF-8 encoding of template files to avoid Chinese content from displaying garbled?

When using AnQi CMS to build and manage a website, you may encounter situations where Chinese content is displayed as garbled characters. This is usually not a problem with the system itself, but rather due to inconsistent encoding of template files.By ensuring that the template file uses UTF-8 encoding, you can completely resolve this problem, allowing the website content to be presented clearly and accurately to visitors. AnQi CMS was designed with the pursuit of efficiency, flexibility, and ease of use. It excels in supporting multiple languages and SEO optimization, and proper coding is the foundation for leveraging these advantages.

2025-11-08

How to choose the appropriate template type for the AnQiCMS website to optimize cross-device display effects?

It is crucial to ensure that the website displays well on different devices when building and operating a modern website.A website that provides a smooth experience on all screen sizes has become a norm as users access websites through various devices such as smartphones, tablets, and computers, not only improving user satisfaction but also helping to effectively disseminate content and optimize search engine rankings.AnQiCMS (AnQiCMS) offers various template types to meet this need, helping us flexibly deal with cross-device display challenges.

2025-11-08

How to customize the display template for specific documents, categories, or single pages?

When using AnQiCMS to manage website content, we often need to assign unique display styles and functional layouts to specific content types or unique pages.This kind of requirement is very common in content operation, for example, a product introduction page may need richer picture display and parameter comparison, while a news article focuses on the reading experience of text;Or it is the "About Us" page on the website, which needs to show a unique corporate culture.AnQi CMS provides flexible template customization features, allowing you to easily meet these personalized display needs

2025-11-08

How to display common website elements, such as headers and footers, uniformly through template fragments (partial)?

When managing website content in Anqi CMS, you may find that many pages have similar structures, such as top navigation, footer copyright information, sidebar, or metadata tags, etc.If you have to write this code repeatedly for each page, it is not only inefficient, but also once you need to modify it, you have to search and update it page by page, which takes time and is prone to errors.Fortunately, Anqi CMS provides a very elegant solution - **template fragments (Partial)**, which helps us manage these common elements efficiently and uniformly.###

2025-11-08