How to use if/else condition judgment to control content display in Anqi CMS template?

Calendar 👁️ 80

In AnQi CMS template creation, flexibly controlling the way content is displayed is the key to improving website user experience and management efficiency.Whether it is to display specific information based on different conditions or to implement more complex personalized layouts, conditional judgment is an indispensable tool.Today, let's delve into how to use the powerfulif/elseCondition judgment to accurately control the presentation of content.

The Anqi CMS template engine uses syntax similar to Django template syntax, which allows web development friends who are familiar with it to get started quickly. Among them,if/elseLogical judgment labels become the core for implementing dynamic content display with their intuitive syntax.

Understandingif/elseBasic syntax

In the Anqi CMS template,if/elseThe basic structure of conditional judgment is similar to that of common programming languages, mainly divided into the following forms:

1. Simpleifthe judgment.When you only need to display content when a certain condition is met and not display when it is not met, you can use the simplestifthe structure.

{% if 条件 %}
    <!-- 满足条件时显示的内容 -->
{% endif %}

2.if-elsetwo-way judgmentWhen you need to choose different content to be displayed in two different situations,if-elsethe structure is very practical.

{% if 条件 %}
    <!-- 满足条件时显示的内容 -->
{% else %}
    <!-- 不满足条件时显示的内容 -->
{% endif %}

3.if-elif-elseMulti-condition judgmentWhen facing more complex scenarios, it is necessary to judge multiple mutually exclusive conditions,if-elif-else(whereelifThe 'else if' abbreviation structure can elegantly handle it for you.

{% if 条件1 %}
    <!-- 满足条件1时显示的内容 -->
{% elif 条件2 %}
    <!-- 满足条件2时显示的内容 -->
{% else %}
    <!-- 所有条件都不满足时显示的内容 -->
{% endif %}

In these conditional statements, you can use various comparison operators (==equal,!=Not equal to,<Less than,>Greater than,<=less than or equal to,>=greater than or equal to) and logical operators (andand,oror,notNon) to construct complex judgment expressions. In addition, you can also use a variable directly as a condition to check if it exists or is empty, for example{% if 变量名 %}.

Actual application scenarios and code examples

Now, let's look at several practical scenariosif/elseThe specific application in Anqi CMS template.

Scenario one: control the display based on the existence of the content

This is the most common application. For example, in a document list, we may only want to display the image when the article has a thumbnail, otherwise skip.

{# 在文章列表循环中,item 代表当前文章对象 #}
{% for item in archives %}
    <div class="article-item">
        <a href="{{ item.Link }}">
            <h3>{{ item.Title }}</h3>
            {% if item.Thumb %}
                <img src="{{ item.Thumb }}" alt="{{ item.Title }}" class="article-thumbnail">
            {% else %}
                <img src="/public/static/images/default-thumb.png" alt="无图替代" class="article-thumbnail-default">
            {% endif %}
            <p>{{ item.Description|truncatechars:100 }}</p>
        </a>
    </div>
{% empty %}
    <p>抱歉,目前没有可展示的文章。</p>
{% endfor %}

Here we utilize{% if item.Thumb %}To judgeitem.ThumbDoes the field have a value. If the image exists, display it; otherwise, display a default placeholder. In addition,{% empty %}IsforA very practical feature in loops, which automatically displays the content when the loop collection is empty, saving extraif archivesjudgment.

Scenario two: Personalized display based on specific attribute values

The AnQi CMS supports setting "recommended attributes" for documents (such as headlines, recommendations, slides, etc).We can use these properties to control the style or display area of different articles on the page.

Suppose we want to make the "头条" article (Flag as "h") more prominent:

{# 在文章列表循环中 #}
{% for item in archives %}
    <div class="article-card {% if item.Flag == 'h' %}highlight-headline{% endif %}">
        {% if item.Flag == 'h' %}
            <span class="badge">头条</span>
        {% elif item.Flag == 'c' %}
            <span class="badge">推荐</span>
        {% endif %}
        <h4><a href="{{ item.Link }}">{{ item.Title }}</a></h4>
        <p>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</p>
    </div>
{% endfor %}

This code passes{% if item.Flag == 'h' %}and{% elif item.Flag == 'c' %}Check the recommended attributes of the article to dynamically add CSS classes or display different labels.

For example, in the navigation menu, we want the link to the current page to be highlighted:

{# 导航列表标签 navList #}
{% navList navs %}
    <ul class="main-nav">
        {% for item in navs %}
            <li class="nav-item {% if item.IsCurrent %}active{% endif %}">
                <a href="{{ item.Link }}">{{ item.Title }}</a>
                {% if item.NavList %} {# 如果有子导航 #}
                    <ul class="sub-nav">
                        {% for subItem in item.NavList %}
                            <li class="sub-nav-item {% if subItem.IsCurrent %}active{% endif %}">
                                <a href="{{ subItem.Link }}">{{ subItem.Title }}</a>
                            </li>
                        {% endfor %}
                    </ul>
                {% endif %}
            </li>
        {% endfor %}
    </ul>
{% endnavList %}

item.IsCurrentIs a boolean value, when the current navigation item matches the page visited by the user, its value istrue. We use{% if item.IsCurrent %}to dynamically addactiveclass to achieve highlighting effect.

Scene three: Display different layouts based on model type

AnQi CMS supports flexible content models. If your website may mix different models (such as articles, products) on the same page and needs to provide different display layouts for them, you can judge through the model ID.

{# 假设在一个综合内容区块中循环所有文档,item 代表文档对象 #}
{% archiveList archives with type="list" limit="5" %}
    {% for item in archives %}
        {% if item.ModuleId == 1 %} {# 如果是文章模型 #}
            <div class="content-article">
                <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
                <p>{{ item.Description }}</p>
                <span class="date">{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
            </div>
        {% elif item.ModuleId == 2 %} {# 如果是产品模型 #}
            <div class="content-product">
                <img src="{{ item.Logo }}" alt="{{ item.Title }}" class="product-image">
                <h4><a href="{{ item.Link }}">{{ item.Title }}</a></h4>
                <p class="price">售价:¥{{ item.Price }}</p>
            </div>
        {% else %} {# 其他未知模型 #}
            <div class="content-generic">
                <a href="{{ item.Link }}">{{ item.Title }} (通用内容)</a>
            </div>
        {% endif %}
    {% endfor %}
{% endarchiveList %}

Byitem.ModuleIdWe can allocate specific display templates and styles for different content models to achieve more refined page control.

Scenario four: Display custom contact information

At the bottom of the website or on the contact us page, it may be necessary to conditionally display different contact methods based on backend configuration.For example, if the administrator fills in WhatsApp, WhatsApp will be displayed, otherwise the regular phone number will be displayed.

`twig

{% contact whatsapp with name="WhatsApp" %}
{% contact phone with name="Cellphone" %}

{% if whatsapp %}
    <p>WhatsApp: <a href="https://wa.me/{{ whatsapp }}" target="_blank" rel="nofollow">{{

Related articles

How to perform initial arithmetic operations on user input data in AnQi CMS template?

In AnQiCMS template design, performing preliminary arithmetic operations on user input data is a key link in achieving dynamic content display and interactive logic.AnQiCMS powerful template engine, draws on the characteristics of Go language and Django templates, providing developers with flexible and easy-to-understand arithmetic calculation capabilities, allowing you to handle various numerical logic in front-end templates without writing complex backend code.

2025-11-08

How to get the friend link in Anqi CMS template and set the nofollow attribute?

In website operation, friendship links are an important means to enhance website authority and obtain external traffic.However, not all friendship links should pass on weight. It is particularly important to use the `rel="nofollow"` attribute reasonably to better manage the SEO performance of the website.The `nofollow` attribute tells search engines not to pass ranking weight from the current page to the target page, which is very useful when linking to non-core content, advertising pages, or third-party websites that cannot be fully trusted, and can effectively avoid SEO risks caused by low-quality links

2025-11-08

How to get the website name in Anqi CMS template and correctly concatenate it in the SEO title?

In website operation, a well-constructed SEO title is crucial for attracting user clicks and improving search engine rankings.It must not only accurately summarize the page content but also ingeniously integrate the brand information.For AnQiCMS users, how to dynamically obtain the website name in the template and correctly concatenate it into the SEO title is a practical and efficient skill.AnQiCMS as a content management system that focuses on SEO optimization, provides very flexible tags at the template level, allowing you to easily achieve this goal.

2025-11-08

How to get the category description with a specified ID in Anqi CMS template and truncate it?

In the Anqi CMS template, effectively managing and displaying category descriptions is a common requirement.Especially when displayed on list pages or block displays, we often need to show a concise introduction of the category rather than a full-length description.This article will provide a detailed introduction on how to obtain the specified ID category description in Anqi CMS template and perform appropriate truncation processing to ensure that the content is both concise and beautiful.Get category description by specified ID In AnQi CMS template, getting category details mainly depends on the `categoryDetail` tag

2025-11-08

How to use a for loop to traverse an array and handle an empty array in Anqi CMS template

During the template development process of AnQi CMS, dynamic data display is one of the core requirements.No matter whether it is an article list, product display, or navigation menu, we cannot do without traversing array or collection data.How to elegantly handle empty data in this process, ensuring the beauty of the page and user experience is equally important.The AnQi CMS template engine supports powerful features similar to Django template syntax, among which the `for` loop is a powerful tool for handling data lists.

2025-11-08

How can I customize the content display layout of the AnQi CMS website?

The layout of website content display is a key factor in attracting visitors, enhancing user experience, and optimizing search engine rankings.A clear, beautiful, and functional layout that can make your website stand out among competitors.AnQiCMS (AnQiCMS) is an efficient content management system that provides high flexibility, allowing you to customize the display of website content according to your actual needs.This article will deeply explore how to customize the content display layout of the Anqi CMS website, helping you turn your creativity into reality and create a website with a unique style.--- ###

2025-11-08

What are the conventions for naming and storing AnQi CMS template files?

When you start using Anqi CMS to build a website, understanding the naming rules and storage path conventions of its template files is the key to efficient website design and content presentation.A clear file structure can not only help you quickly locate and modify templates, but also make team collaboration smoother, ensuring stable operation of the website. ### The "home" of template files: unified storage location All template files of AnQi CMS are stored centrally in the `/template` folder under the project root directory.This is like a large library, where all books (template topics) are collected here

2025-11-08

How to effectively organize and reference website static resources (CSS/JS/images)?

Building and managing websites in AnQiCMS (AnQiCMS), efficient organization and referencing of static resources (CSS styles, JavaScript scripts, images, etc.) is the key to improving website performance, ease of maintenance, and user experience.Our Anqi CMS provided us with clear guidelines and practical features, helping us easily cope with these challenges. ### One: A Clear and Ordered Directory Structure: The Way to Organize Static Resources Good file organization is the foundation of efficient management of static resources.In AnQi CMS

2025-11-08