How to perform conditional judgments (if/else) in Anqi CMS template to control content display?

Auto CMS template development skills: Flexibly use condition judgment (if/else) to control content display

In website content operations, we often need to display or hide specific content blocks based on different conditions, or differentiate the display based on different data states. The powerful template engine of AnQiCMS (AnQiCMS) provides us with flexible conditional judgment capabilities, through the clever use ofif/elseThe statement allows you to easily implement fine-grained control over content, making your website more dynamic and user-friendly.

The template syntax of Anqi CMS borrows from the Django template engine, its logical tags are usually prefixed with{% %}and variable outputs are enclosed in double curly braces{{ }}。Understanding this basic rule is the premise of mastering conditional judgment.

Understandingif/elseThe basic syntax of conditional judgment.

The core of conditional judgment is{% if 条件 %}Label. It allows you to check if a condition is true and display different content based on the result.

1. Basic.ifstatementWhen you only want to display content under certain conditions and do not display any specific content otherwise, you can use the simplestifstructure:

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

This example shows that if the current article (archive) has images (HasImage is true), the article's logo image will be displayed.

2.if-elsestructureIf you want to display different content when the condition is met and not met,if-elsethe structure is your ideal choice:

{% if user.IsLoggedIn %}
    <p>欢迎回来,{{ user.Name }}!</p>
{% else %}
    <p>请<a href="/login">登录</a>或<a href="/register">注册</a>。</p>
{% endif %}

Here judge whether the user is logged in, and display different welcome messages or guides according to the login status.

3.if-elif-elseMultiple conditional judgmentsWhen you need to handle multiple mutually exclusive conditions, you can useelif(else if) to expand the judgment logic:

{% if archive.Flag == "h" %}
    <span class="flag-headline">头条</span>
{% elif archive.Flag == "c" %}
    <span class="flag-recommend">推荐</span>
{% else %}
    <span class="flag-normal">普通文章</span>
{% endif %}

This example is based on the recommended attributes of the articleFlag) to display different tags, such as "Top News", "Recommendation", or "Normal Article".

In conditional judgments, you can use common comparison operators, such as==(equals,)!=(not equal to,)>(greater than,)<(less than,)>=(greater than or equal to,)<=(less than or equal to). At the same time,and/or/notthese logical operators can also help you build more complex judgment logic. For example:{% if item.IsCurrent and item.HasChildren %}.

Flexible application of conditional judgment in real scenarios

1. Control the display of list content and 'default' stateWhen displaying an article list or product list, if the list is empty, you may not want the page to display a blank space, but rather give the user a friendly prompt. Safe CMS'sforloop tag built-inemptyKeyword, it can elegantly handle this situation:

{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
        <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
    {% empty %}
        <p>抱歉,当前分类或搜索条件下暂无内容。</p>
    {% endfor %}
{% endarchiveList %}

WhenarchivesAn empty list will automatically display:<p>抱歉,当前分类或搜索条件下暂无内容。</p>This text avoids the page from being empty.

2. Dynamically activate the navigation menu statusWhen building the navigation menu, we often need to highlight the current page the user is on. Using the navigation list tag (navList)} returned byIsCurrentproperty, it can be easily achieved:

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

Whenitem.IsCurrentWhen it is true,<li>the tag will be addedactiveClass, so that highlighting can be controlled through CSS.

3. Prompt for comment review status.When displaying user comments, in order to comply with content standards or conduct manual review, some comments may be in a pending review status. At this time, we can useitem.Statususe properties for judgment:

{% commentList comments with archiveId=archive.Id type="list" limit="6" %}
    {% for item in comments %}
        <div>
            {% if item.Status != 1 %} {# 假设Status=1表示审核通过 #}
                <span>审核中:{{ item.UserName|truncatechars:6 }}</span>
            {% else %}
                <span>{{ item.UserName }}</span>
            {% endif %}
            <p>{{ item.Content }}</p>
        </div>
    {% endfor %}
{% endcommentList %}

So, users can clearly see which comments are still under review.

4. Customize the display of fields based on the content model.The auto CMS supports flexible content model custom fields. You can control the display based on the existence or value of these custom fields:

{# 假设有一个自定义字段叫 'special_note' #}
{% archiveDetail specialNote with name="special_note" %}
{% if specialNote %}
    <div class="alert alert-info">特别提示:{{ specialNote }}</div>
{% endif %}

Here check if the article has a 'special_note' field, if it does, display the prompt in special style.

Enhance judgment ability with filters.

The template filters (Filters) of AnQi CMS can process variables and then use the processed results for conditional judgments, which greatly enhances the flexibility of the template. Filters use|symbols to concatenate.

  • |lengthFilter: Determine the length of a string or listIf you need to determine whether the length of a text exceeds a certain threshold or whether a list contains elements:

    {% if archive.Description|length > 50 %}
        <p>{{ archive.Description|truncatechars:50 }}...</p>
        <a href="{{ archive.Link }}">阅读更多</a>
    {% else %}
        <p>{{ archive.Description }}</p>
    {% endif %}
    

    Here, the length of the article abstract is judged, if it exceeds 50 characters, it is truncated and the "Read More" link is displayed.

  • |containFilter: Determine if the string contains a specific substringWhen you need to check if a string variable contains a specific keyword,|containthe filter is very useful:

    {% set contactInfo = contact.Cellphone %} {# 获取联系电话 #}
    {% if contactInfo|contain:"888" %}
        <p>这是一个VIP客服电话:{{ contactInfo }}</p>
    {% else %}
        <p>联系电话:{{ contactInfo }}</p>
    {% endif %}
    

    This example simply checks if "888" is included in the contact phone number and uses it to determine whether to display as VIP customer service.

  • |dumpFilter: auxiliary debuggingDuring development, if the conditional judgment does not work as expected,|dumpFilter is a very useful debugging tool, which can print out the structure, type and value of variables: “`twig {{ archive|dump }} {% if debug_mode %} {# There is a debug_mode variable assumed #}

    <pre>{{ archive