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

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