How to use conditional judgment and loop control to dynamically adjust the display of content?

Calendar 👁️ 75

In Anqi CMS, we often encounter scenarios where we need to display different information based on specific conditions, or repeat a series of contents.At this time, by flexibly using conditional judgment and loop control, the website content can become more vivid and intelligent.

The AnQiCMS template function provides strong syntax support similar to the Django template engine, through these tags, we can easily achieve dynamic content adjustment without writing complex background code.

Conditional judgment: make the content 'speak to people'

Conditional judgment is the basis for dynamic content display. Imagine if your website needs to target different user groups or display different information in specific situations, conditional judgment comes into play.In AnQi CMS, we mainly use{% if ... %}Tags to build conditional logic.

A basic conditional judgment structure is as follows:

{% if 条件表达式 %}
    <!-- 当条件为真时显示的内容 -->
{% else %}
    <!-- 当条件为假时显示的内容 -->
{% endif %}

If we need to handle multiple cases, we can use{% elif ... %}Add more judgment branches:

{% if 条件表达式1 %}
    <!-- 当条件1为真时显示的内容 -->
{% elif 条件表达式2 %}
    <!-- 当条件2为真时显示的内容 -->
{% else %}
    <!-- 当所有条件都为假时显示的内容 -->
{% endif %}

Such conditional judgments can bring many conveniences in practical applications.

For example, you may want to display the image only when a thumbnail exists in a document:

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

For example, we can display "In stock" or "Out of stock" on the product details page according to the product's inventory situation:

{% archiveDetail productStock with name="Stock" %}
{% if productStock > 0 %}
    <span style="color: green;">有货</span>
{% else %}
    <span style="color: red;">缺货</span>
{% endif %}

Sometimes, we may need to load different styles or content modules based on the current page category ID. For example, when the category ID is 10, a special promotional banner is displayed:

{% categoryDetail currentCategoryId with name="Id" %}
{% if currentCategoryId == 10 %}
    <div class="special-promo-banner">
        <h2>此分类独享优惠!</h2>
        <p>立即购买享受更多折扣。</p>
    </div>
{% endif %}

By flexible applicationand/or/notWith logical operators, we can build more complex conditional expressions to make the display logic of content more refined. For example, when the article is recommended as a headlineandWhen the publication time is within the past week, display a 'Hot New Article' tag:

{% archiveDetail articleFlag with name="Flag" %}
{% archiveDetail articleCreatedTime with name="CreatedTime" %}
{% set oneWeekAgo = stampToDate(now().timestamp - 7 * 24 * 60 * 60, "2006-01-02 15:04:05") %}

{% if articleFlag == 'h' and articleCreatedTime > oneWeekAgo %}
    <span class="badge hot-new">热门新文</span>
{% endif %}

Loop control: Efficiently organize and display content

In website content management, the most common need is to list a large number of articles, products, categories, or comments.It is not realistic to add one by one, at this point, loop control becomes crucial.Support for AnQi CMS templates{% for ... in ... %}Tags, used to traverse various data sets.

A typical loop structure is like this:

{% for item in 数据集合 %}
    <!-- 针对每个item显示的内容 -->
{% endfor %}

If the data set may be empty, we can also add one in the loop:{% empty %}Block, to provide a friendly prompt when there is no data, avoid blank pages:

{% for item in 数据集合 %}
    <!-- 针对每个item显示的内容 -->
{% empty %}
    <!-- 当数据集合为空时显示的内容 -->
{% endfor %}

For example, list the latest 10 articles:

<ul class="article-list">
    {% archiveList latestArticles with type="list" limit="10" order="id desc" %}
        {% for article in latestArticles %}
        <li>
            <a href="{{ article.Link }}">{{ article.Title }}</a>
            <span class="date">{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
        </li>
        {% empty %}
        <li>暂时还没有任何文章。</li>
        {% endfor %}
    {% endarchiveList %}
</ul>

In the loop, we can also take advantage offorloopVariables to get the current state of the loop, such as which element it is, whether it is the first or last element, etc. This is very useful for applying special styles to lists:

<div class="product-gallery">
    {% archiveList products with type="list" categoryId="1" limit="5" %}
        {% for product in products %}
        <div class="product-item {% if forloop.Counter == 1 %}first-product{% elif forloop.Revcounter == 1 %}last-product{% endif %}">
            <img src="{{ product.Thumb }}" alt="{{ product.Title }}" />
            <h3>{{ product.Title }}</h3>
            {% if forloop.Counter == 1 %}
                <p class="highlight">本店主推!</p>
            {% endif %}
        </div>
        {% empty %}
        <p>抱歉,该分类下暂时没有产品。</p>
        {% endfor %}
    {% endarchiveList %}
</div>

forloop.CounterCounts starting from 1,forloop.RevcounterCounts backwards from the total number of the set.

Furthermore,cycleThe tag can alternate output predefined values in a loop, often used to add alternating background colors or other styles to list items:

<ul class="comment-list">
    {% commentList comments with archiveId=archive.Id type="list" limit="10" %}
        {% for comment in comments %}
        <li class="comment-item {% cycle 'odd' 'even' %}">
            <strong>{{ comment.UserName }}</strong>: {{ comment.Content }}
            <span class="time">{{ stampToDate(comment.CreatedTime, "2006-01-02 15:04") }}</span>
        </li>
        {% empty %}
        <li>暂无评论,快来发表您的看法吧!</li>
        {% endfor %}
    {% endcommentList %}
</ul>

Combine and use to create a more intelligent display

The combination of conditional judgment and loop control can create a more functional and better user experience dynamic content display.

For example, at the bottom of the article detail page, we usually display related articles. We can first loop to get the related articles, but if there are no related articles, then display a default recommendation list:

<div class="related-articles">
    <h3>相关推荐</h3>
    {% archiveList related with type="related" limit="5" %}
        {% for item in related %}
            <a href="{{ item.Link }}">{{ item.Title }}</a>
        {% empty %}
            <!-- 如果没有相关文章,显示一些通用推荐 -->
            {% archiveList defaultRecommendations with type="list" limit="5" order="views desc" %}
                {% for item in defaultRecommendations %}
                    <a href="{{ item.Link }}">精选:{{ item.Title }}</a>
                {% endfor %}
            {% endarchiveList %}
        {% endfor %}
    {% endarchiveList %}
</div>

Another common application scenario is to adjust the display based on the user-defined content model fields. For example, if the product model has a custom fieldmaterial(Material), we can display different icons or descriptions based on its value:

”`twig {% archiveDetail productMaterial with name=“material” %}

<!-- ... 其他产品信息 ... -->
{% if productMaterial == 'wood' %}
    <span class="material-icon wood-icon">木质</span>
{% elif productMaterial == 'metal' %}
    <span class="material-icon metal-icon">金属</span>
{% else %}
    <span class="material-icon default-icon">未知材质

Related articles

How to display variables in AnQiCMS templates?

In AnQiCMS templates, how to effectively display variable data is a core skill that every website operator and template creator needs to master.AnQiCMS uses a syntax similar to the Django template engine, making data calls and display both intuitive and flexible.This article will delve into various ways to display variables in AnQiCMS templates, helping you accurately present dynamic information such as backend configuration data and article content on the website front-end.

2025-11-08

What file extension should AnQiCMS template files use to ensure correct display?

When using AnQiCMS for website construction and content management, ensuring that the template files are displayed correctly is the foundation for the normal operation of the website.This is where, the naming convention of template files, especially the file extension, plays a crucial role. The template files of Anqi CMS have a clear and unified file extension requirement, which is to use **.html** as the file extension of the template files.These files are usually organized in the `/template` folder under the root directory of the website.Choose `.html`

2025-11-08

How to configure different content display templates for mobile and PC separately?

In website operation, providing a good browsing experience for different devices is crucial.AnQi CMS knows this, it provides a flexible template mechanism, allowing you to easily configure different content display templates for mobile and PC terminals, thereby meeting user needs and improving website performance.Below, let's take a detailed look at how to achieve this goal in Anqi CMS.### Understanding AnQi CMS Template Mode AnQi CMS provides three main website modes to meet the needs of content display on mobile and PC platforms in different scenarios: 1.

2025-11-08

How can I customize a template for a specific category or page to control the display style?

When operating a website, we often encounter situations where different types of content, even articles in the same category or different "About Us" pages on the same website, hope to have a unique display style to better attract readers and convey information.AnQiCMS (AnQiCMS) is well aware of this need and therefore provides a very flexible template customization mechanism, allowing us to easily tailor the display style for specific categories or pages.The Anqi CMS template system is based on the Django template engine syntax in Go language, which means that as long as you have a basic understanding of front-end development

2025-11-08

Why is UTF8 encoding crucial for the display of content in AnQiCMS templates?

## Content display no longer troubles: Why is UTF-8 encoding so critical for AnQiCMS templates?In the process of building and operating a website with AnQiCMS, we often strive for the website's efficiency, stability, and diverse display of content.However, there is a seemingly basic but actually crucial link that, if not handled properly, will cause all our efforts to be wasted - that is the character encoding of the template file.Especially for AnQiCMS, UTF-8 encoding is not just a recommendation, it is the core foundation to ensure that website content is displayed correctly and clearly.

2025-11-08

Where should the mobile-specific template file be stored to be recognized by AnQiCMS?

Provide special optimization for the mobile experience of the website in AnQiCMS (AnQiCMS), which is a very practical requirement.Benefiting from the flexible template mechanism of AnQiCMS, we can easily achieve this goal.When it is necessary to provide a set of independent template files for mobile devices, the storage location and configuration method of these templates are crucial.

2025-11-08

How does AnQiCMS automatically apply the default display template for documents or categories through naming conventions?

In website operation, template management is the key to ensuring the professionalism and consistency of content display.For many operators, manually selecting or specifying a template for each new article or category is undoubtedly a repetitive and time-consuming task.AnQi CMS understands this pain point, therefore it introduces a set of intelligent naming conventions, allowing the system to automatically identify and apply default display templates, thereby greatly simplifying our daily operations.The cleverness of this feature lies in AnQiCMS's ability to intelligently associate content with preset design styles according to the specific naming rules of template files

2025-11-08

How does the `template_type` setting in `config.` affect the overall display mode of the website?

AnQiCMS (AnQiCMS) is an efficient and flexible content management system that provides great convenience to our users.During the process of building and operating a website, there is a core configuration file called `config.`, which plays a vital role in each template directory.

2025-11-08