How does the AnqiCMS template use if/else tags for conditional judgments to dynamically display different content?

Calendar 👁️ 70

In website content operation, we often need to flexibly display different content modules or styles based on different conditions, in order to enhance user experience and page interaction. AnqiCMS (AnqiCMS) provides powerful template tag functions, among whichif/elseThe conditional label is the core tool to achieve this goal.With it, we can easily make the website content come alive according to specific rules, no longer monotonous static display.

The basic conditional judgment in AnqiCMS template:ifTag

In the AnqiCMS template system, conditional judgments use syntax similar to Django template engine.ifTags are the starting point of all condition judgments, and their basic structure is{% if 条件 %}and{% endif %}. WhenifWhen the condition inside the tag is evaluated as true, the content wrapped by it will be rendered and displayed on the page; if the condition is false, this content will be ignored.

This “condition” can be very flexible, it can be the existence of a variable, whether the value of a variable equals a specific string or number, or even a combination of multiple conditions. For example, if you want to check whether the current document has a thumbnail and decide whether to display the image accordingly, you can use it like this:

{% if archive.Thumb %}
    <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}">
{% endif %}

Herearchive.ThumbIs a variable, if it has a value (i.e., the thumbnail exists), the condition is true, and the image will be displayed.This simple judgment is very useful when it is necessary to adjust the page layout according to the integrity of the content.

Expand condition judgment:elifandelse

SingleifTags are usually not enough to deal with complex business logic. In order to handle various possibilities, the Anqi CMS template introduceselif(else if abbreviation) andelse.

  • elifTag: used in the firstifIf the condition is not met, continue to check other conditions. You can set multipleeliftags to cover different situations.
  • elseTag: as the last 'safety net' option, when allifandelifconditions are not met, elseThe content within the tags will be displayed.

Combine these three tags, and we can build more refined logical branches. Imagine a scenario where you want to base your recommendations on the current document's attributes (in AnqiCMS'sarchive.Flag) to display different tags:

{% if archive.Flag == "h" %}
    <span class="flag-hot">热门头条</span>
{% elif archive.Flag == "c" %}
    <span class="flag-recommend">编辑推荐</span>
{% elif archive.Flag == "f" %}
    <span class="flag-slide">幻灯展示</span>
{% else %}
    <span class="flag-normal">普通内容</span>
{% endif %}

This code checks the recommended attributes of the document in order, if it matches 'h' it displays 'Hot News', if it is not 'h' then check whether it is 'c', etc., if none of the above conditions are met, it finally displays 'Normal Content'.This way greatly enhances the expressive power and dynamic content of the template.

Examples of actual application scenarios

if/elseTags are widely used in the template design of AnQi CMS, and the following are some common practical scenarios:

  1. Navigation is displayed differently based on whether the category has subcategories.When building multi-level navigation, you may want only the parent categories that contain subcategories to display the dropdown menu. BycategoryListtags to get the category data after, you can useitem.HasChildrenproperties for judgment:

    {% categoryList categories with moduleId="1" parentId="0" %}
        {% for item in categories %}
            <li>
                <a href="{{ item.Link }}">{{ item.Title }}</a>
                {% if item.HasChildren %}
                    <ul>
                        {% categoryList subCategories with parentId=item.Id %}
                            {% for subItem in subCategories %}
                                <li><a href="{{ subItem.Link }}">{{ subItem.Title }}</a></li>
                            {% endfor %}
                        {% endcategoryList %}
                    </ul>
                {% endif %}
            </li>
        {% endfor %}
    {% endcategoryList %}
    

    So, only whenitem.HasChildrenThe list of subcategories will be rendered when true.

  2. Display contact information dynamicallyYour website's footer may need to display multiple contact methods, but some methods may not be desired to always be displayed. ThroughcontactThe label retrieves the contact information set in the background and can judge whether the corresponding field has a value:

    {% contact contactInfo with name="Wechat" %}
    {% if contactInfo %}
        <p>微信:{{ contactInfo }}</p>
    {% endif %}
    
    {% contact qrcodeInfo with name="Qrcode" %}
    {% if qrcodeInfo %}
        <img src="{{ qrcodeInfo }}" alt="微信二维码">
    {% endif %}
    

    They will be displayed on the page only when the background has set WeChat or WeChat QR code.

  3. Control the display of images or contentOn the list page or detail page, you may need to adjust the layout based on whether the document has a thumbnail or if the content is complete.

    {% archiveList archives with type="list" limit="5" %}
        {% for item in archives %}
            <div class="article-item">
                {% if item.Thumb %}
                    <a href="{{ item.Link }}"><img src="{{ item.Thumb }}" alt="{{ item.Title }}"></a>
                {% endif %}
                <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
                {% if item.Description|length > 0 %} {# 判断描述内容是否存在或长度大于0 #}
                    <p>{{ item.Description }}</p>
                {% else %}
                    <p>暂无简介。</p>
                {% endif %}
            </div>
        {% endfor %}
    {% endarchiveList %}
    

    This has been useditem.ThumbTo determine if there is a thumbnail anditem.Description|length > 0To determine if the description content is empty, thereby achieving a more refined display.

  4. Display content based on user group permissionsIf your website has a membership system or VIP feature, you may want to display different content based on the user's level. Suppose you have obtained the information of the currently logged-in user (for examplecurrentUserVariables that containGroupId)

    {% if currentUser.GroupId == 2 %} {# 假设2是VIP用户组ID #}
        <div class="vip-exclusive-content">
            这是VIP用户专属内容!
        </div>
    {% else %}
        <div class="general-content">
            请升级为VIP查看更多内容。
        </div>
    {% endif %}
    

    This method can help you easily manage paid content or member-only content.

**Practice and Precautions

  • Keep the code clear: To improve readability, it is recommended toif/elseStructure should be properly indented. Avoid overly complex nesting. If the logic is too complex, consider whether it can be split into different template fragments or simplified through backend configuration.
  • Check if the variable existsBefore determining the value of the variable, it is best to confirm that the variable itself exists to avoid potential template parsing errors. For example,{% if archive.Title %}Instead of using directly{% if archive.Title == '特定标题' %}Safer, because it will judge firstarchive.TitleIf there is a value.
  • Escaping HTML content:Whenif/elseWhen you need to output content containing HTML code inside the tag, be sure to use|safethe filter. For example{{ archive.Content|safe }}This will tell the template engine that this content is safe and does not require HTML escaping, ensuring that the content can be rendered correctly in the HTML structure.
  • Condition combinationIniforelifIn Chinese, you can useand/or/notlogical operators to combine multiple conditions, such as{% if item.HasChildren and item.IsCurrent %}.
  • Performance consideration: Althoughif/elseExtremely flexible, but too many complex condition judgments may slightly increase the page rendering time.In most cases, this impact is negligible, but for high-traffic pages, it is recommended to optimize the logic to the fullest extent while ensuring functionality, and avoid unnecessary calculations.

Masterif/elseThe use of tags is a basic and important skill in the development of Anqi CMS templates.It endows the website with strong dynamics and personalized capabilities, allowing you to better control the way content is presented to meet various operational needs.


Frequently Asked Questions (FAQ)

Q1:ifWhat types of data comparisons do the condition judgment in the tags support?A1: Anqi CMS'ifThe label supports various types of data comparisons. You can directly check if a variable exists (for example{% if archive.Title %}), and also perform numerical comparisons (==,!=,<,>,<=,>=), string comparisons (==,!=), and boolean value comparisons (== true,== falseOr directly using the variable itself, as well as logical combination judgments (and,or,not). Moreover|length) for more complex judgments.

Q2: Why is myifTags sometimes display the opposite of what I expect, or there may be a situation where the content does not display?A2: This is usually due to the following reasons:

1.  **变量不存在或为空**:如果您尝试判断一个不存在或为空的变量(例如一个没有缩略图的 `archive.Thumb`),它通常会被评估为 `false`。
2.  **数据类型不匹配**:例如,您试图将一个字符串“1”与数字 `1` 进行严格的 `==` 比较时,可能会出现不匹配。确保您比较的数据类型是兼容的,或者进行适当的类型转换(尽管模板引擎通常会尝试自动转换)。
3.  **逻辑运算符优先级**:当使用 `and` 和 `or` 组合多个条件时,它们的优先级可能会导致意外结果。在需要时,可以使用括号来明确指定运算顺序,尽管安企CMS的模板语法中并不直接支持条件表达式内的括号。在这种情况下,最好拆分成多个 `if/elif` 块。
4.  **`|safe` 过滤器遗漏**:如果条件判断的区块内包含HTML内容,但忘记使用 `|safe` 过滤器,那么HTML代码会被转义,导致内容显示为原始代码而非渲染后的效果。

Q3: How toifJudge multiple conditions at the same time?A3: You can useand(Logical AND),or(Logical OR) andnotCombine multiple conditions with (logical NOT).

*   **`and`**: 所有条件都必须为真,整个表达式才为真。例如:`{% if item.HasChildren and item.IsCurrent %}`。
*   **`or`**: 只要有一个条件为真,整个表达式就为真。例如:`{% if item.Price > 100 or item.Flag == "f" %}`。
*   **`not`**: 反转条件的真假。例如:`{% if not archive.Thumb %}`(如果文档没有缩略图)。

Through these logical operators

Related articles

How to implement pagination navigation in AnqiCMS templates and customize the display of page numbers and style?

In a content management system, especially when a website carries a large amount of articles, products, or other list information, reasonable pagination navigation is the key to improving user experience and facilitating content browsing.It can not only help visitors quickly find the information they need, but also avoid the slow loading caused by too long single-page content, and it is also very beneficial for search engine optimization (SEO).AnqiCMS provides a powerful and flexible template tag set, allowing you to easily implement pagination functionality on your website and customize its display style and appearance as needed.### Enable pagination feature: Starting from the list tag At

2025-11-09

How to display the AnqiCMS backend management's friend links on the front page and control the Nofollow attribute?

In website operation, friendship links are an important means to enhance website authority, attract traffic, and strengthen industry associations.However, how to effectively manage these links, especially in terms of search engine optimization (SEO), ensuring that they can play a positive role while not causing negative effects on their own website, is a concern for many operators.AnqiCMS as a content management system dedicated to providing efficient and customizable solutions offers very convenient and flexible tools in this regard.

2025-11-09

How to build and display AnqiCMS's message form on the front page, supporting custom fields and captcha?

In website operation, establishing effective interaction with visitors is a key step to improve user experience and collect valuable feedback.Anqi CMS knows this point well, therefore it provides us with a powerful and flexible feedback form function, which not only supports basic feedback collection but also allows for easy customization of fields and captcha, making the website's interactive module efficient and secure.Next, we will delve into how to build and display a fully functional comment form on the front page of Anqi CMS, supporting custom fields and captcha, thereby better serving our users.

2025-11-09

How to display the AnqiCMS comment list on the front page and support pagination and parent-child comment display?

AnQi CMS provides a convenient comment function for website content interaction, allowing visitors to express their opinions on articles, products, and other content.For website operators, how to clearly display these comments on the website front-end and provide user-friendly pagination and parent-child comments (i.e., reply function) is a key link to improving user experience.Below, let's discuss how to achieve this goal in AnQi CMS.

2025-11-09

How to iterate through data using the for loop tag in AnqiCMS templates and display list content on the front end?

In modern website construction, content lists are everywhere, whether it is article lists, product displays, user comments, or navigation menus, they cannot do without efficient organization and presentation of data.AnqiCMS as an enterprise-level content management system based on Go language, provides intuitive and powerful loop tags in template creation, allowing you to easily display various list content on the front page.

2025-11-09

How to format a timestamp in AnqiCMS template to display a custom date and time format?

In AnqiCMS, managing website content, we often need to display the publication time, update time, or registration and login time of users, etc.These time information is usually stored in the database in the form of a timestamp, which is a series of numbers.If displayed directly on the website front end, these numbers are not intuitive and lack aesthetics.Fortunately, AnqiCMS provides very flexible template tags, allowing us to easily format these timestamps into the date and time display format we want.AnqiCMS template system

2025-11-09

How to use with or set tags in AnqiCMS templates to define variables for optimizing content display and maintenance?

In AnqiCMS template development, defining and using variables are indispensable skills to make our website content more flexible and code easier to maintain.The system uses a syntax similar to the Django template engine, where `with` and `set` tags are used to define variables, optimizing content display and managing templates effectively.Understanding and using them effectively can make your website operation twice as effective.Why do we need to define variables in the template?

2025-11-09

How to use AnqiCMS template include tag to introduce common code fragments and achieve page structure reuse?

In website content management, we often encounter situations where it is necessary to display the same content blocks, such as headers, footers, sidebars, or navigation menus, on multiple pages.If you copy and paste this code every time, it is not only inefficient, but also when you need to modify it, you have to face the繁琐 of repeated operations in multiple files.If this continues, the maintenance and updates of the website content will become extremely difficult, and inconsistencies in the experience may even occur.

2025-11-09