How to implement conditional judgment in AnQiCMS template to control the display of content?

Calendar 👁️ 61

In AnQi CMS template design, flexibly controlling the display of content is the key to building dynamic, responsive websites.Whether it is to display different information based on the page type, data status, or specific conditions, conditional judgment is an indispensable tool.AnQiCMS's template engine provides an intuitive and powerful conditional judgment mechanism, allowing you to easily implement these complex logic.

Basic syntax of conditional judgment

AnQiCMS template condition judgment is similar to many mainstream template engines, using{% if ... %}A tag structure. It allows you to decide whether a part of the template should be rendered based on the truth or falsity of one or more conditions.

The basic conditional judgment structure is as follows:

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

If you need to handle more complex logic, you can introduce{% elif ... %}(else if) and{% else %}(otherwise) tags to handle multiple mutually exclusive conditions:

{% if 条件一 %}
    <!-- 当条件一为真时显示的内容 -->
{% elif 条件二 %}
    <!-- 当条件一为假且条件二为真时显示的内容 -->
{% else %}
    <!-- 当所有条件都为假时显示的内容 -->
{% endif %}

InifInside the tag, you can perform various comparisons and logical operations.For example, determine if a variable exists, whether it is equal to a specific value, whether it contains a certain keyword, or combine multiple conditions.

Common conditional judgment scenarios and practices

In the operation of actual websites, the application scenarios of conditional judgment are very extensive. The following lists some common usage scenarios and implementation methods:

  1. Determine if a variable exists or has a valueThis is one of the most common uses, especially when displaying images, descriptions, or custom fields.If a data field may be empty, by checking whether it exists or has a value, you can avoid the page from displaying incomplete or erroneous information.

    {% if archive %} {# 判断整个文档对象是否存在 #}
        <h1>{{ archive.Title }}</h1>
        {% if archive.Thumb %} {# 判断文档缩略图是否存在 #}
            <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}">
        {% else %}
            <img src="/static/images/default-thumb.jpg" alt="默认缩略图">
        {% endif %}
    {% else %}
        <p>抱歉,您要查找的文档不存在。</p>
    {% endif %}
    

    For list data, there is also a special optimization method for determining if the list is empty. Inforthe loop, you can use{% empty %}tags to handle the case where the list is empty, which is better than writing one separately.ifJudgment is more concise:

    {% for item in archives %}
        <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
    {% empty %}
        <li>目前还没有任何文章。</li>
    {% endfor %}
    
  2. Comparison of numbers or stringsWhen you need to display content based on a number (such as ID, views) or a string (such as title, status), you can directly compare:

    {# 判断当前文档ID是否为特定值 #}
    {% if archive.Id == 10 %}
        <p>这是一篇非常重要的精选文章!</p>
    {% endif %}
    
    {# 根据系统设置决定显示内容 #}
    {% if system.SiteCloseTips %}
        <div class="site-closed-message">
            <p>{{ system.SiteCloseTips }}</p>
        </div>
    {% endif %}
    

    The AnQiCMS template supports various comparison operators, such as equal==, not equal to!=, greater than>, less than<and greater than or equal to>=and less than or equal to<=.

  3. Combination of logical operatorsBy logical operators, you can combine multiple conditions to achieve more complex judgment logic:

    • &&orand: Logical 'AND', true only when all conditions are true.
    • ||oror: Logical 'OR', true if any condition is true.
    • !ornot: Logical 'NOT', the negation.
    • in: Check if a value exists in a list or string.

    For example, the navigation menu is highlighted only when it is on the current page and has a submenu:

    {% if item.IsCurrent && item.NavList %}
        <li class="active has-submenu">
            <a href="{{ item.Link }}">{{ item.Title }}</a>
            <!-- 显示子菜单 -->
        </li>
    {% else %}
        <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
    {% endif %}
    

    Another example, to determine if the article title contains a specific keyword:

    {% if archive.Title|contain:"限时优惠" %}
        <span class="badge sale-tag">限时优惠中!</span>
    {% endif %}
    
  4. Combine the filter for more advanced judgmentFilters can process variables before they are used for conditional judgment or display, which greatly expands the ability of conditional judgment.

    • |contain: "关键词": Determine if a string or array contains a specific keyword.
    • |length: Get the length of a string, array, or key-value pair, commonly used to judge the amount of content.
    • |yesno:"真值,假值,未知值": Map boolean values or variables that can be evaluated as boolean values to a custom string representation.

    For example, determine if there are comments in the comment list and display the number of comments:

    {% commentList comments with archiveId=archive.Id type="list" %}
        {% if comments|length > 0 %}
            <p>共有 {{ comments|length }} 条评论。</p>
            {% for comment in comments %}
                <!-- 显示评论详情 -->
            {% endfor %}
        {% else %}
            <p>还没有评论,快来发表您的看法吧!</p>
        {% endif %}
    {% endcommentList %}
    

    Determine if a status value is 'Published':

    {% if archive.Status|yesno:"已发布,草稿,待审核" == "已发布" %}
        <span class="status-published">已发布</span>
    {% endif %}
    
  5. Determine the state of the current page.The AnQiCMS template automatically identifies the type of the current page (document detail page, category list page, single page, etc.), and you can use this contextual information for conditional judgments. For example, only show related recommendations on the document detail page:

    {# 假设`archive`变量只在详情页存在 #}
    {% if archive %}
        <h3>相关推荐</h3>
        {% archiveList relatedArchives with type="related" limit="5" %}
            <ul>
            {% for item in relatedArchives %}
                <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
            {% endfor %}
            </ul>
        {% endarchiveList %}
    {% endif %}
    

Points to note

  • grammatical accuracy:if/elif/else/endiftags must be paired and the syntax must be precise, including%symbols and spaces.
  • variable names and case sensitivityThe variable names of AnQiCMS templates are usually camel case and case sensitive. Please refer to the tag document to ensure the spelling of variable names is correct.
  • Content escaping: AnQiCMS template defaults to escaping output variables to prevent XSS attacks. If you are sure that the output content is safe HTML code (such as rich text editor content), please use|safea filter such as{{ archive.Content|safe }}.
  • Testing and debuggingIn practical applications, be sure to thoroughly test various combinations of conditions to ensure that the content is displayed as expected.

By proficiently using these conditional judgment techniques, you will be able to fully utilize the potential of the AnQiCMS template to provide users with a more intelligent and personalized website experience.


Frequently Asked Questions (FAQ)

Q1: How do I determine if the current page is a specific document detail page or a category list page?

**A

Related articles

How to format a timestamp and display it as a readable date and time in AnQiCMS?

In website content operation, time information plays an indispensable role.Whether it is the publication time of the article, the shelf date of the product, or the submission time of the comments, a clear and readable date and time format can greatly enhance the user experience.AnQi CMS as an efficient content management system, fully considers this point, and provides a flexible way to format and display these timestamp data.### Understanding Timestamps in AnQi CMS In the AnQi CMS backend, when we publish articles, products, or perform other content management operations

2025-11-08

How to get and display the list of friendship links configured in the AnQiCMS background?

In website operation, friendship links play an indispensable role. They not only bring valuable external traffic to the website but also help improve search engine optimization (SEO) effects, enhance the authority and credibility of the website.For users using AnQiCMS, managing and displaying friend links is a simple and efficient process.This article will introduce in detail how to configure friend links in the AnQiCMS background, as well as how to elegantly present them in your website front-end template.In AnQiCMS admin manage friend links First

2025-11-08

How to generate and display the website's message form in AnQiCMS templates?

In website operation, an efficient and convenient feedback form is an important bridge for user interaction with the website.It not only collects user feedback, but also serves as the entry point for potential customers to obtain information.AnQiCMS as an enterprise-level content management system provides powerful and flexible functions in this aspect, allowing us to easily generate and manage comment forms in templates.

2025-11-08

How to display the comment list of a document in AnQiCMS and implement pagination?

In Anqi CMS, adding a comment list to the document page and implementing pagination is a key step to enhancing user interaction experience.This can not only let visitors participate in discussions and share opinions, but also brings more vitality to the website content.AnQi CMS provides intuitive and powerful template tags, allowing us to easily implement these features. ### Integrate the comment feature into your document detail page Comment lists and comment forms are typically integrated into the detail page of the document.

2025-11-08

How to use a for loop to traverse data and display it in the AnQiCMS template?

AnQiCMS with its flexible and powerful template system makes content display efficient and expressive.For website operators and developers, mastering how to traverse and display data in templates is a key step to unlocking their powerful features and bringing the website content to life.Today, let's delve into how to use the `for` loop in AnQiCMS templates to easily present your dynamic data.AnQiCMS's template engine adopts syntax similar to Django, which allows users familiar with other mainstream template languages to quickly get started.

2025-11-08

How to use AnQiCMS filters to truncate or convert text to uppercase and lowercase?

AnQiCMS provides powerful flexibility in content display, its template engine is built-in with a rich set of filters, helping users to easily process text without modifying the original content, including truncation and case conversion.These filters make the presentation of front-end content more accurate and beautiful, meeting the display needs of different scenarios.In AnQiCMS template syntax, the use of filters is very intuitive.You can apply a filter by adding a pipe symbol (`|`) after the variable name, if the filter requires parameters, then use a colon (`:`) after the filter name

2025-11-08

How to display the mobile URL of the website in AnQiCMS template?

When using AnQiCMS to build and manage websites, many friends may encounter such a need: If the website has an independent mobile version, how can you conveniently obtain and display the URL of this mobile website in the template?This makes it convenient for users to switch between different devices, and it also has a positive impact on search engine optimization (SEO).Don't worry, AnQiCMS provides a very intuitive way to achieve this.Why do we need to display the mobile URL in the template?First, let's talk about why there is such a need

2025-11-08

How to display the path of static files (CSS/JS/images) in AnQiCMS template?

When building a website with AnQiCMS, the correct reference to static files (such as CSS stylesheets, JavaScript scripts, and images) is the basis for ensuring the normal operation and beautiful presentation of the website.AnQiCMS provides us with a clear and flexible mechanism for managing and displaying these file paths, whether it is the static resources built into the template or the media files uploaded through the backend, there is a convenient way to reference them.

2025-11-08