How to use the `if` tag for conditional judgment to control content display in AnQiCMS templates?

Calendar 👁️ 68

How to use in AnQiCMS templates?ifTags perform conditional judgments to control content display?

When building website templates, we often need to display or hide specific content blocks based on different conditions.For example, an image is displayed only when the article has a thumbnail, or a welcome message is displayed only when the user logs in.ifThe tag is a powerful tool for implementing this conditional judgment.It uses syntax similar to Django template engine, concise and expressive, making the content display logic clear and easy to understand.

Core concept: What isifTag?

ifThe tag is a control structure used for logical judgment in the AnQiCMS template.Its main function is to determine whether to render the content inside based on the truth value of a certain condition expression.When the condition is true, the content inside the tag will be output to the final HTML page; when the condition is false, this part of the content will be ignored.This allows the template to flexibly adjust the display of the page according to changes in data or context.

The most basicifThe tag structure is as follows:{% if 条件表达式 %} <!-- 当条件为真时显示的内容 --> {% endif %}

ifTags appear in pairs and must be presented with{% endif %}end.

Basic Usage: Single condition judgment

The most common usage is to check if a variable exists or its value is "true":

{# 假设有一个名为 `archive` 的文档对象 #}
{% if archive %}
    <p>当前页面存在文档内容。</p>
{% endif %}

{# 检查 `archive.Thumb` 是否存在,存在则显示缩略图 #}
{% if archive.Thumb %}
    <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}">
{% endif %}

In AnQiCMS templates, the following values are considered "false":false/nilan empty string""numbers0and empty lists or dictionaries. Any other value is usually considered 'true'.

Advanced usage: multi-condition judgment and branch

When you need to handle more complex logic,iftags can be used in conjunction withelif(else if abbreviation) andelseUsed to build multi-branch conditional judgment structures.

{% if archive.Views > 1000 %}
    <p>这篇文章非常受欢迎,阅读量超过1000!</p>
{% elif archive.Views > 500 %}
    <p>这篇文章有一定热度,阅读量超过500。</p>
{% else %}
    <p>这篇文章的阅读量尚不明显。</p>
{% endif %}

In this example, the system will first checkarchive.ViewsDoes it exceed 1000? If true, display the first text; otherwise, continue checking.archive.ViewsIs greater than 500. If true, then display the second paragraph; if the above conditions are not met, then finally displayelseContent in the tag.

Common types of judgment conditions

ifThe conditional expression of the label can be very flexible, supporting various data types and operators:

  1. Does the variable exist or is not emptyThis is the most common judgment, write the variable name directly. If the variablenilis an empty string or0/falsean empty set, it is considered false.

    {% if system.SiteIcp %} {# 检查网站备案号是否存在 #}
        <a href="https://beian.miit.gov.cn/" rel="nofollow" target="_blank">{{ system.SiteIcp }}</a>
    {% endif %}
    
    {% if contact.Cellphone %} {# 检查联系电话是否存在 #}
        电话: {{ contact.Cellphone }}
    {% endif %}
    
  2. Numerical comparison: Use==(equals,)!=(not equal,)>(greater than,)<(less than,)>=(greater than or equal to,)<=(Less than or equal to) comparison operator.

    {% if archive.Id == 10 %} {# 检查文档ID是否为10 #}
        <p>这是ID为10的特殊文档。</p>
    {% endif %}
    
    {% if item.Price < 100 %} {# 检查商品价格是否低于100 #}
        <span class="sale-price">{{ item.Price }}</span>
    {% endif %}
    
  3. Boolean value judgment: Directly judge the truth or falsity of a boolean variable or expression, you can usenotkeyword to negate.

    {% if item.IsCurrent %} {# 检查当前导航项是否是当前页面 #}
        <li class="active">{{ item.Title }}</li>
    {% else %}
        <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
    {% endif %}
    
    {% if not pages.PrevPage %} {# 如果没有上一页 #}
        <span class="disabled">上一页</span>
    {% endif %}
    
  4. String/set contains: UseinThe operator can check if a value exists in a string, an array (slice), or a dictionary (map).

    {% set tags = "AnQiCMS, Go, Web" %}
    {% if "Go" in tags %} {# 检查标签字符串是否包含 "Go" #}
        <p>这是一个关于 Go 语言的文档。</p>
    {% endif %}
    
    {% set categories = ["新闻", "博客", "产品"] %}
    {% if "产品" in categories %} {# 检查数组是否包含 "产品" #}
        <p>分类列表中有产品分类。</p>
    {% endif %}
    
  5. Logical combination: Useand(AND),or(OR) operator combines multiple conditions.

    {% if archive.Views > 100 and archive.CommentCount > 10 %} {# 同时满足两个条件 #}
        <p>热门且讨论度高的文章。</p>
    {% endif %}
    
    {% if user.IsAdmin or user.IsVip %} {# 满足任一条件 #}
        <p>欢迎尊贵的会员/管理员!</p>
    {% endif %}
    

Examples of actual application scenarios

1. Show/Hide document thumbnail

In the article list or detail page, show the thumbnail if the article has one, otherwise do not show.

{% archiveList archives with type="list" limit="5" %}
    {% for item in archives %}
        <div class="article-item">
            <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
            {% if item.Thumb %} {# 如果存在缩略图 #}
                <a href="{{ item.Link }}">
                    <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
                </a>
            {% endif %}
            <p>{{ item.Description }}</p>
        </div>
    {% endfor %}
{% endarchiveList %}

2. Highlight the current item in the navigation menu

Based onitem.IsCurrentProperty to add navigation items corresponding to the current pageactiveClass.

{% navList navs %}
    <ul>
        {% for item in navs %}
            <li {% if item.IsCurrent %}class="active"{% endif %}>
                <a href="{{ item.Link }}">{{ item.Title }}</a>
            </li>
        {% endfor %}
    </ul>
{% endnavList %}

3. Control the display status of the pagination button

In the pagination component, disable or hide the corresponding buttons based on whether there is a previous page or next page.

`twig {% pagination pages with show=“5” %}

<div class="pagination-controls">
    {% if pages.FirstPage.IsCurrent %}
        <span class="disabled">首页</span>
    {% else %}
        <a href="{{ pages.FirstPage.Link }}">首页</a>
    {% endif %}

    {% if pages.PrevPage %}
        <a href="{{ pages.PrevPage.Link }}">上一页</a>
    {% else %}
        <span class="disabled">上一页</span>
    {% endif %}

    {# 中间页码循环 #}
    {% for pageItem in pages.Pages %}
        {% if pageItem.IsCurrent %}
            <span class="current">{{ pageItem.Name }}</span>
        {% else %}
            <a href="{{ pageItem.Link }}">{{ pageItem.Name }}</a>
        {% endif %}
    {% endfor %}

    {% if pages.NextPage %}
        <

Related articles

How to dynamically retrieve and display the contact information of the website in AnQiCMS?

In today's digital age, a website's contact information is more than just cold numbers or addresses; it is a bridge for users to build trust and communicate with the company.Efficiently and accurately display this information on the website, and be able to update it flexibly as needed, which is crucial for any website operator.AnQiCMS as an enterprise-level content management system provides a very intuitive and powerful solution in this aspect, allowing you to easily manage these key information without touching complex code.This article will introduce how to configure and dynamically obtain the contact information of the website in AnQiCMS

2025-11-08

How to display the document list under a specific Tag in AnQiCMS?

In AnQiCMS, tags (Tag) are a powerful and flexible way to organize content, allowing you to associate documents in multiple dimensions without relying on traditional hierarchical classification structures.When you want to display all documents under a specific topic or keyword, it is particularly important to show the document list under a specific tag.This not only helps visitors find the content they are interested in faster, but also effectively improves the internal link structure and SEO performance of the website.

2025-11-08

How to retrieve and display the friend link list in AnQiCMS template?

In website operation, friendship links are an important factor in improving website authority, increasing external traffic, and optimizing user experience.AnQiCMS (AnQiCMS) is well aware of this, and therefore provides a convenient friend link management function in system design, and supports flexible calling and display in templates.This article will provide a detailed introduction on how to retrieve and display the friend link list in your AnQiCMS template.### Management of friendship links: Starting from the background Before starting the template call, make sure that your website's background has configured the friendship links

2025-11-08

How to display the Tag list associated with the article in AnQiCMS?

In AnQiCMS, effectively managing and displaying the tag (Tag) list of articles can not only help with content organization but also significantly improve the internal link structure and search engine optimization (SEO) effect of the website.Labels as a flexible classification method can link articles across categories and themes, providing users with a richer browsing path. ### Manage and create article tags in the background First, understanding how to add and manage article tags in the AnQiCMS background is fundamental.

2025-11-08

How to use a `for` loop to iterate over data and display content in AnQiCMS templates?

In AnQiCMS template development, we often need to display a series of dynamic content, such as the latest article list, product categories, navigation menu items, and even custom parameters.At this point, the 'for loop' has become the core tool for us to traverse these data and display it on the web page.Understand and master the `for` loop, which will greatly enhance the flexibility and development efficiency of the template.### Core Grammar: The Foundation of Data Traversal The `for` loop syntax in AnQiCMS templates is concise and intuitive, borrowing the style of the Django template engine.

2025-11-08

How to format a timestamp (timestamp) into a readable date format for display in AnQiCMS?

In the process of website operation, the effective display time of content publishing or updating is crucial for improving user experience and the readability of content.If time information is presented in the original timestamp format, it is often difficult for ordinary users to understand.AnQiCMS provides a straightforward and flexible way to help you convert these digital timestamps into easily readable date and time formats.### How AnQiCMS handles timestamps AnQiCMS typically uses standard Unix Timestamp format for storing content time information

2025-11-08

How to truncate a string and add an ellipsis (...) to limit the display length in AnQiCMS template?

In AnQiCMS template development, we often need to refine the content displayed on the website, such as article titles, summaries, or abstracts of a text.If the content is too long, it not only affects the beauty of the page, but may also reduce the user's reading experience.AnQiCMS's powerful template engine provides a simple and efficient method to solve this problem, allowing us to easily extract strings and automatically add ellipses (...) to elegantly limit the display length of content.

2025-11-08

How to safely output HTML code in the template without escaping in AnQiCMS?

When using AnQiCMS for website template development or content display, you may encounter situations where you need to output HTML code directly on the page, only to find that the code is automatically escaped, for example, the `<p>` tag becomes `&lt;This often confuses those who are new to it.In fact, this is the default measure taken by the AnQiCMS template engine for website security.### Understanding the default security mechanism of AnQiCMS templates The AnQiCMS template engine design has drawn inspiration from

2025-11-08