How to control content conditional judgment and loop display in AnQiCMS with Django template engine syntax?

Calendar 👁️ 75

Use Django template syntax to make AnQiCMS content display more flexible conditional judgment and loop

The strength of AnQiCMS lies not only in its efficient and stable backend architecture, but also in the great flexibility it provides for front-end content display for content operators.Among them, deeply integrating the Django template engine syntax allows us to build like a child's blocks, easily control the display of website content through simple conditional judgments and loops, creating more intelligent and user-friendly dynamic pages.

This article, let's delve into how to skillfully use Django template engine conditional judgment in AnQiCMS{% if %}) and loop display({% for %}Function, brings vitality to the website content.

Understand conditional judgment: Let the content 'taste the dish according to the person.'

Imagine, you want certain content to appear only under specific conditions, such as only displaying to VIP users, or highlighting articles with a 'recommended' tag, or showing exclusive promotional information on a particular holiday. At this point,{% if %}The tag becomes our helpful assistant, it can decide whether to render a section of HTML code according to the conditions you set.

In AnQiCMS templates, the syntax of conditional judgments is very intuitive, usually starting with{% if 条件 %}and ends with{% endif %}end.

Basic usage: single condition judgment

The simplest conditional judgment is based on a boolean value (True or False). For example, we want to determine whether an article has a thumbnail, and if it does, display it:

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

here,archive.ThumbIf there is a value (non-empty), the condition is true, and the image will be displayed.

Multiple choices:{% else %}and{% elif %}

If you want to provide an alternative solution when the condition is not met, we can introduce{% else %}For example, when an article does not have a thumbnail, a default placeholder image is displayed:

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

When the situation is more complex and it is necessary to judge multiple mutually exclusive conditions,{% elif %}(else if abbreviation) can be used. For example, based on the recommended attributes of the article(Flag) show different prompts:

{% if archive.Flag == "h" %}
    <span class="badge badge-hot">头条</span>
{% elif archive.Flag == "c" %}
    <span class="badge badge-recommend">推荐</span>
{% else %}
    <!-- 其他情况,不显示标签 -->
{% endif %}

Here, we comparearchive.FlagThe value determines whether to display the label 'Headlines' or 'Recommendations.' It is worth noting that conditional judgments support various comparison operators, such as==(equals,)!=(not equal,)>(greater than,)<(less than,)>=(greater than or equal to,)<=(less than or equal to), as well asin(inclusive) andnot(Not) logical operators, which allow us to build very complex judgment logic. For example, determining whether an ID is in a certain list:{% if item.Id in selectedIds %}.

Master the cyclic display: Efficiently present a large amount of information

When we need to display a series of contents, such as the latest article list, product categories, or image gallery, it is obviously unrealistic and inefficient to write them individually. At this time,{% for %}The loop tag becomes our helpful assistant, it can traverse the array or list data obtained by AnQiCMS through various tags (such asarchiveList,categoryList,navListetc) and display them one by one.

Basic Usage: Traverse list data

In AnQiCMS, we usually use a tag to get the data list first, then use{% for %}The tag to iterate over. For example, get the latest 10 articles and display their titles and links:

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

here,articlesIsarchiveListThe article list returned by the tag,articleIs the variable for the current article in each loop.

Handle empty list:{% empty %}

When processing list data, we often encounter the situation where the list is empty. To avoid the page from appearing blank or unfriendly prompts,{% empty %}tags provide an elegant solution. When{% for %}When the loop data is empty,{% empty %}the content in it will be rendered:

{% archiveList products with type="list" categoryId=currentCategory.Id limit="8" %}
    <ul>
        {% for product in products %}
            <li>
                <a href="{{ product.Link }}">{{ product.Title }}</a>
            </li>
        {% empty %}
            <li>抱歉,该分类下暂无产品。</li>
        {% endfor %}
    </ul>
{% endarchiveList %}

Enhanced loop control:forloopVariables,reversedandcycle

{% for %}Some special tags are provided inside the loop.forloopA variable that can help us better control the loop:

  • forloop.Counter: The current loop iteration number, starting from 1.
  • forloop.Revcounter: The reverse sequence number of the current loop, starting from the total count.
  • forloop.First: A boolean value, which is True if it is the first item in the loop.
  • forloop.Last: Boolean value, if the current is the last item in the loop, it is True.

Using these variables, we can achieve many practical effects, such as adding numbers to list items or highlighting the first article:

{% archiveList articles with type="list" limit="5" %}
    <ol>
        {% for article in articles %}
            <li {% if forloop.First %}class="highlight-first"{% endif %}>
                {{ forloop.Counter }}. <a href="{{ article.Link }}">{{ article.Title }}</a>
            </li>
        {% endfor %}
    </ol>
{% endarchiveList %}

In addition, we can also use{% for item in list reversed %}Reverse iterate through the list, or utilize{% cycle 'odd' 'even' %}Tags to alternate the odd and even row styles of list items.

Combine to build a smarter dynamic page.

The real strength lies in combining conditional judgment and loop display to build highly dynamic and intelligent pages.

For example, when building a multi-level navigation menu, you can first iterate through the first-level categories, and then use{% if item.HasChildren %}to determine if there are subcategories, if there are, continue to iterate through the subcategories:

{% navList mainNavs %}
    <ul class="main-menu">
        {% for item in mainNavs %}
            <li {% if item.IsCurrent %}class="active"{% endif %}>
                <a href="{{ item.Link }}">{{ item.Title }}</a>
                {% if item.NavList %} {# 判断是否有下级导航 #}
                    <ul class="sub-menu">
                        {% for subItem in item.NavList %}
                            <li {% if subItem.IsCurrent %}class="active"{% endif %}>
                                <a href="{{ subItem.Link }}">{{ subItem.Title }}</a>
                            </li>
                        {% endfor %}
                    </ul>
                {% endif %}
            </li>
        {% endfor %}
    </ul>
{% endnavList %}

In this example, we not only displayed the main navigation in a loop, but also through{% if item.NavList %}Determined if there was a child navigation and performed a nested loop. This greatly improved the flexibility and maintainability of the navigation.

For example, show related recommendations on the article detail page and decide whether to display the image based on whether the article has a cover image:

`twig

Related articles

What are the requirements for the `.html` suffix and `/template` directory structure of the template file in terms of content display?

In AnQiCMS, whether the content can be presented correctly and elegantly to the user largely depends on the organization and naming conventions of the template files.Understanding these basic conventions can help you design and manage website interfaces more efficiently, ensuring accurate content presentation.### The Foundation of Template Files: `/template` Directory and `.html` Suffix AnQiCMS has clear regulations for the placement of template files: all template files must be stored in the `/template` folder under the root directory of the website

2025-11-07

How does AnQiCMS ensure the compliance and security of displayed content through security mechanisms?

In today's digital age, the security and compliance of website content are the core challenges faced by operators.Users expect to browse safe and harmless information, search engines favor high-quality compliant content, and various regulations also have strict requirements for the dissemination of online information.As a system dedicated to providing an efficient and customizable content management solution, AnQiCMS has integrated content security mechanisms and compliance guarantees into its core functions from the very beginning, striving to build a stable and reliable content publishing platform for users.AnQiCMS ensures the journey of display content compliance and security

2025-11-07

How static caching and SEO optimization can improve the loading speed and search engine friendliness of website content?

The loading speed of website content and search engine-friendliness are the two indispensable cornerstones of modern website operations.They not only directly affect user experience, but are also key factors in determining the ranking of a website in search engines.As a content management system, AnQiCMS (AnQi CMS) took these two points into full consideration from the beginning of its design, providing strong support for operators through static caching and a series of SEO optimization tools.Static caching: The unsung hero of website acceleration

2025-11-07

How does the flexible permission control mechanism ensure the operation safety of different administrators for content display?

How to ensure that your content operations are both secure and flexible in AnQi CMS?Today, with the rapid explosion of digital content, efficient and secure content management has become the cornerstone of corporate operations.For those who have multiple brand websites, content teams, or self-media operators, how to ensure that different team members work safely and efficiently within their respective responsibilities while avoiding misoperation or abuse of privileges is a major challenge for content management systems.

2025-11-07

How does AnQiCMS handle template files with different encoding formats to avoid garbled content display?

One of the most annoying problems when using a website content management system is the display of garbled characters, especially when the website involves multiple languages or imports content from different sources.This chaos not only affects user experience, but may also damage the professional image of the website.AnQiCMS is a system dedicated to providing an efficient and customizable content management solution, with a clear strategy for handling template file encoding, aiming to help users eliminate乱码 from the root.The core lies in AnQiCMS's unified requirements for **UTF-8 encoding**. UTF-8

2025-11-07

How does the adaptive template, code adaptation, and PC + mobile mode affect the display of content on different devices?

AnQiCMS content management system provides powerful flexibility in content presentation, especially for display effects on different devices.It supports three template modes of "adaptive", "code adaptation", and "PC + independent mobile site", allowing us to finely control the display of content on computers, tablets, and mobile phones according to specific needs.Understanding the working principle of these patterns is crucial for ensuring user experience and optimizing website performance.First, let's understand **Adaptive Mode**.In adaptive mode, the website uses a set of templates and styles

2025-11-07

How to configure AnQiCMS Apache reverse proxy to correctly display website content?

AnQiCMS is an efficient content management system developed based on the Go language, which usually runs on a specific port of the server, such as the default port 8001.In order for users to access the website through common domain names instead of adding a port number at the end of the address, we need to configure a reverse proxy.

2025-11-07

How do the new model features in AnQiCMS v2.1.1 affect the display logic of articles and products?

Since its launch, AnQiCMS has been favored by users for its concise, efficient, and flexible features.In the latest v2.1.1 version, we welcome a major feature update - a brand new 'Model' feature.This seemingly technical improvement actually has a profound impact on the way we publish and display website content on a daily basis, especially for core content types such as articles and products.Model Function: Blueprint of Content Structure In simple terms, "model" is like a blueprint or skeleton for content. In the past

2025-11-07