How to use the `if` tag in AnQiCMS templates to determine if a variable is empty, exists, or has a specific value?

Calendar 👁️ 67

In AnQiCMS template development,ifTags are the core tools for building dynamic page content. They allow us to flexibly control the display of content based on different conditions, thereby providing users with a more intelligent and personalized browsing experience.Whether you want to determine whether a piece of data exists, whether it is empty, or want to adjust the layout based on a specific value,ifTags can easily help you achieve that.

AnQiCMS's template engine syntax is very similar to the Django template engine, so developers familiar with this syntax will feel very亲切.ifThe basic structure of labels is intuitive and easy to understand, including{% if 条件 %}/{% elif 其他条件 %}(optional),{% else %}(optional) and{% endif %}. Through this structure, we can clearly define the logical flow of content.

Determine if the variable exists or is not empty

In practical applications, one of the most common needs is to determine whether a variable has a value or is empty. AnQiCMS'sifThe label follows a concept of 'truth value' when judging variables. Simply put, for most variables, if they are:

  • non-empty strings (such as"Hello World")
  • non-zero numbers (such as10/3.14)
  • non-empty list, array, or mapping
  • notnilof the object

they will beiflabeled as 'True'. Conversely, an empty string""numbers0, an empty list/array/map as wellnilis considered "False".

Therefore, to determine whether a variablearchive.TitleDoes it exist and have content, the simplest way is to use it directly:

{% if archive.Title %}
    <h1>{{ archive.Title }}</h1>
{% else %}
    <h1>暂无标题</h1>
{% endif %}

If we need to explicitly determine whether a variable isan empty string, we can also use the equality operator:

{% if archive.Description == "" %}
    <p>该文章暂无简介。</p>
{% else %}
    <p>{{ archive.Description }}</p>
{% endif %}

For a list or array variable, for examplearchive.Images(which may contain multiple images), to determine if it contains images, it is usually combinedlengthwith a filter to get its length:

{% if archive.Images|length > 0 %}
    <div class="gallery">
        {% for img in archive.Images %}
            <img src="{{ img }}" alt="图片">
        {% endfor %}
    </div>
{% else %}
    <p>暂无相关图片。</p>
{% endif %}

Of course, you can also usenotReverse judgment using keywords, for example{% if not archive.Thumb %}Used to determine if the thumbnail field is empty or does not exist.

Determine if the variable is a specific value

In addition to checking for existence or non-empty,ifThe tag is powerful because it can drive content display based on the specific value of the variable. This includes numerical comparisons, string matching, and boolean judgments.

Numerical judgment:We can use common comparison operators:==(equal to),!=(Not equal),>(greater than),<(Less than),>=(Greater than or equal),<=(Less than or equal).

For example, based on the number of views of the article:archive.ViewsTo display different recommendation levels:

{% if archive.Views > 1000 %}
    <span class="hot-badge">热门文章</span>
{% elif archive.Views > 500 %}
    <span class="popular-badge">受欢迎</span>
{% else %}
    <span class="new-badge">普通阅读</span>
{% endif %}

String judgment:When a variable is of string type, it can be directly compared with a specific string. For example, the AnQiCMS template can usesystemtags to get the current language setting of the websitesystem.LanguageWe can display different prompts based on this:

{% if system.Language == "zh-cn" %}
    <p>欢迎访问我们的中文网站!</p>
{% elif system.Language == "en-us" %}
    <p>Welcome to our English website!</p>
{% else %}
    <p>Hello World!</p>
{% endif %}

Boolean value judgment:If the variable itself is a boolean value(trueorfalse)the judgment will be more direct. For example, for an article'sFlagProperties may contain boolean judgments (although the documentFlagProperties are strings or characters; here we assume custom fieldsIsFeaturedare boolean values):

{% if archive.IsFeatured %}
    <div class="featured-banner">特别推荐</div>
{% endif %}

To determine if an element exists in a collection (inoperator)

AnQiCMS template also providedinThe operator makes it convenient to check whether a value exists in a set (such as a list, array, or a key of a mapping). This is very practical when dealing with labels, permissions, or categorization scenarios.

For example, if a document may have multipleTagAssuming we want to determine if a document contains a specific tag name:

{# 假设我们有一个名为 'tags' 的列表,其中包含当前文章的所有标签名 #}
{% set tags = archive.Tags|split:"," %} {# 假设 Tags 字段是逗号分隔的字符串,先用 split 过滤器转换成列表 #}
{% if "AnQiCMS" in tags %}
    <span class="tag-highlight">AnQiCMS 相关</span>
{% endif %}

Or, if an element's attribute value is a list, determine whether a certain identifier is in the list:

{% if 'h' in archive.Flag %} {# 假设 archive.Flag 是一个包含多个字母的字符串,可以视为集合判断 #}
    <span class="flag-h">头条</span>
{% endif %}

Apply in real-world scenarios

We have mastered these basic judgment methods, and we can implement various complex logic in the AnQiCMS template.

For example, on the article detail page, we usually display the links to the previous and next articles.But if the current article is the first or last one, the corresponding link should not be displayed. At this time,ifThe tags can be put into use:

<nav class="pagination-nav">
    {% prevArchive prev %}
        {% if prev %}
            <a href="{{ prev.Link }}">上一篇:{{ prev.Title }}</a>
        {% else %}
            <span>没有上一篇了</span>
        {% endif %}
    {% endprevArchive %}

    {% nextArchive next %}
        {% if next %}
            <a href="{{ next.Link }}">下一篇:{{ next.Title }}</a>
        {% else %}
            <span>没有下一篇了</span>
        {% endif %}
    {% endnextArchive %}
</nav>

Another common example is to display different content blocks on the homepage, such as only showing the article list under a certain category when there is content in that category:

`twig {% categoryList categories with moduleId=“1” parentId=“0” limit=“4” %}

{% for category in categories %}
    {% if category.ArchiveCount > 0 %} {# 判断分类下是否有文章 #}
        <section class="category-section">
            <h2><a href="{{ category.Link }}">{{ category.Title }}</a></h2>
            <ul class="article-list">
                {%

Related articles

How to implement multi-condition logical judgment with the `if` tag in AnQiCMS template (OR/&&, AND/||, NOT/!)?

In AnQiCMS template development, mastering conditional logic judgment is the key to building dynamic and intelligent web pages.Among them, the `if` tag is the core of controlling content display, not only supporting simple boolean judgments, but also being able to flexibly implement logical combinations of multiple conditions, such as "and" (`&&`), "or" (`||`), and "not" (`!`)`etc. Understanding and skillfully using these logical operators can help us control the display and hiding of template elements more finely, thereby creating a more interactive and customizable user experience.### Basic Conditional Judgment: `if`

2025-11-09

How does the `yesno` filter combine with the data list in AnQiCMS templates to display the specific status of each piece of data?

During the process of building a website with AnQiCMS, we often need to display various data on the front-end page, which often has different states.For example, is an article published or a draft, a product listed or not, or is a user active or not.How to clearly and intuitively present these states to the user while keeping the template code concise and readable is a common concern for content operations and template developers.Today, let's delve into a very practical tool in AnQiCMS——the `yesno` filter

2025-11-09

In AnQiCMS template, can the `yesno` filter determine the true or false state of a numeric or string variable?

In AnQiCMS template development, in order to better control the display logic of content, we often need to judge the 'true or false' status of a variable.This is a very practical tool, the `yesno` filter.It can help us output different texts in a concise way based on the status of variables, and it can even handle numeric and string type variables.The `yesno` filter is designed to provide a straightforward way to handle ternary states: yes, no, and uncertain (or no value).The basic working principle is to parse the input variable into a boolean value (true or false)

2025-11-09

How to set the internationalized text for three states in the `yesno` filter of AnQiCMS template for a multilingual website?

How to ensure that the dynamic text in the template of a multilingual website can be displayed correctly according to the visitor's language settings is a challenge often faced by website operators.AnQiCMS (AnQiCMS) relies on its flexible template engine and strong multilingual support to provide an elegant solution.Today, let's delve into how the `yesno` filter of the AnQiCMS template can be combined with the internationalization mechanism in a multilingual website to accurately present three status texts.### Get to know `yesno`

2025-11-09

How to construct complex conditional display logic in AnQiCMS templates using `if`, `elif`, and `else` structures?

In AnQiCMS template design, dynamically displaying content is a key factor in enhancing website interactivity and user experience.When we need to decide what and how to display on the page based on specific data conditions, the `if`, `elif` (short for else if), and `else` conditional tags are particularly important.They have given the template flexible logical control capabilities, allowing our website to meet various complex display needs.The condition judgment syntax of the AnQiCMS template engine is similar to many programming languages, it is very intuitive and easy to understand

2025-11-09

How to use the `not` operator to reverse conditional judgments in AnQiCMS templates?

The AnQiCMS template system is renowned for its flexibility and efficiency, drawing inspiration from Django's template engine syntax, making content presentation and logical control intuitive.In template development, we often need to display or hide content based on different conditions, at this point, mastering the various usages of conditional judgment is particularly important.Today, let's talk about how to cleverly use the `not` operator in AnQiCMS templates to reverse condition judgments, making your page logic clearer and more flexible.What is the `not` operator?

2025-11-09

The `in` operator in the AnQiCMS template's `if` statement, how to judge whether an element exists in an array or set?

When developing the AnQiCMS website template, we often need to dynamically display or hide content based on certain conditions.A common requirement is to determine whether an element exists within a dataset, such as checking if a user has a specific role or if the current article has a specific tag.AnQiCMS's template engine provides a concise and powerful `in` operator that can easily solve such problems. ### Core Function Explanation: What is the `in` operator?The design inspiration of AnQiCMS template engine comes from Django

2025-11-09

How to avoid excessive nesting of `if` statements in AnQiCMS templates to improve code readability?

In AnQiCMS template development, we often encounter situations where we need to display different content based on different conditions.Newcomers may tend to use the `{% if condition %}` statement extensively. As the project requirements grow, these conditional judgments become nested layer by layer, which quickly makes the template difficult to read, maintain, and even hides potential logical errors.Code readability once reduced, not only will the development efficiency be affected, but the future feature iteration and problem troubleshooting will also become extremely difficult.Fortunate is that AnQiCMS is based on Go language Django-like

2025-11-09