How does AnqiCMS template use if/else tags for conditional judgment and 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 interactivity. AnqiCMS provides powerful template tag functions, whereif/elseConditional judgment tags are the core tools to achieve this goal.Through it, we can easily make the website content come alive according to specific rules, no longer monotonous static display.

AnqiCMS template conditional judgment basis:iftags

In the AnqiCMS template system, conditional judgments are made using syntax similar to Django template engine.ifTags are the starting points of all condition judgments, their basic structure is{% if 条件 %}and{% endif %}). WhenifThe content within the tag is rendered and displayed on the page when the condition is evaluated to true; if the condition is false, this content will be ignored.

This 'condition' can be very flexible, it can be whether a variable exists, whether the value of a variable is equal to 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 practical when adjusting the page layout according to the completeness of the content.

Expand condition judgment:elifandelse

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

  • eliftags: used in the firstifCondition not met, continue to check other conditions. You can set multipleeliftags to cover different situations.
  • elsetags: as the last 'safety net' option, when allifandelifconditions are not met,elseThe content within the tag will be displayed.

Combining these three tags, we can build more refined logical branches. Imagine a scenario where you want to recommend attributes of the current document based on (AnqiCMS ofarchive.Flag) to display different marks:

{% 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 %}

Examples of practical application scenarios

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

  1. Based on whether there are subcategories in the classification, different navigation will be displayedWhen building multi-level navigation, you may want only the parent categories that contain subcategories to display the dropdown menu. ThroughcategoryListLabel fetches category data after,item.HasChildrenuse properties 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 %}
    

    In this way, only whenitem.HasChildrenThe child category list will be rendered only when it is true.

  2. Dynamic display of contact informationYour website's footer may need to display multiple contact methods, but some methods may not be desired to always be displayed. BycontactThe label can retrieve contact information from the background settings and then determine if 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 %}
    

    Only when WeChat or WeChat QR code is set in the background, will they be displayed on the page.

  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 whether 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 %}
    

    Here, we useitem.ThumbTo determine whether there is a thumbnail,item.Description|length > 0To determine whether the description content is empty, thereby achieving 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. Assuming you have obtained the information of the currently logged-in user (for example,currentUserVariable, which containsGroupId).

    {% 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 exclusive member content.

**Practice and Precautions

  • Keep the code clearEnglish for readability, it is recommended toif/elseStructure it with proper indentation. Avoid overly complex nesting, and consider splitting into different template fragments or simplifying through backend configuration if the logic is too complex.
  • Note if the variable exists: It is best to confirm whether the variable itself exists before judging its value to avoid potential template parsing errors. For example,{% if archive.Title %}Instead of using directly{% if archive.Title == '特定标题' %}More secure, as it will check firstarchive.Titleif there is a value.
  • Escape HTML content: whenif/elsewhen you need to output content containing HTML code inside tags, please make sure to use|safea filter. For example{{ archive.Content|safe }}This will inform the template engine that the content is safe and does not require HTML escaping, thus ensuring that the content can be rendered correctly with the HTML structure.
  • Conditional combination: IniforelifEnglishand/or/notEnglish{% if item.HasChildren and item.IsCurrent %}.
  • Performance considerationsAlthoughif/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 maximum extent while ensuring the functionality, and avoid unnecessary calculations.

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


Common Questions (FAQ)

Q1:ifEnglishA1: Anqi CMSifLabel supports comparison of various types of data. You can directly judge if a variable exists (for example{% if archive.Title %}), or perform numerical comparison (==,!=,<,>,<=,>=), string comparison (==,!=), or boolean value comparison (== true,== falseor directly use the variable itself), and logical combination judgment(and,or,not). Moreover, it can also be combined with filters (such as)|length) for more complex judgments.

Q2: WhyifTags sometimes display the opposite of what I expect or do not display the content?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 toifTags check multiple conditions at the same time?A3: You can useand(Logical AND),or(Logical OR) andnotUse (logical NOT) to combine multiple conditions.

*   **`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