How can conditional judgments (if/else) be used in the AnQi CMS template to control content display?

Calendar 👁️ 58

Skills for developing Anqi CMS templates: flexibly using conditional judgment (if/else) to control content display

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

The template syntax of Anqi CMS draws inspiration from the Django template engine, where logical tags are usually enclosed by{% %}and variable output is done using 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.ifStatement.When you only want to display content when a certain condition is met and do not display any specific content when it is not met, you can use the simplestifStructure:

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

In this example, if the current article (archive) has an image (HasImage is true), it will display the article's logo image.

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 we judge whether the user is logged in, and display different welcome messages or guides according to the login status.

3.if-elif-elseMulti-condition judgmentWhen you need to handle multiple mutually exclusive conditions, you can useelif(else if) to extend 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 article(Flag) to display different tags, such as 'Top News', 'Recommended', or 'Normal Article'.

In conditional statements, you can use common comparison operators such as==(equal to),!=(Not equal),>(greater than),<(Less than),>=(Greater than or equal),<=(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 %}.

Apply flexible conditional judgment in practical scenarios

1. Control the display of list content and 'default' stateWhen displaying a list of articles or products, if the list is empty, you may not want the page to display a blank space, but to give the user a friendly prompt. Anqi CMS'sforLoop tags are built-inemptyKeywords 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 %}

WhenarchivesThe list will be automatically displayed when it is empty<p>抱歉,当前分类或搜索条件下暂无内容。</p>This text avoids the empty page.

2. Dynamically activate the navigation menu stateWhen building a navigation menu, we often need to highlight the current page the user is on. Using the navigation list label (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>Tags will be addedactiveClass, so as to control highlighting through CSS.

3. Prompt for comment review statusWhen displaying user comments, in order to comply with content standards or for manual review, some comments may be in a pending review status. At this time, we can useitem.Statusproperties 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 %}

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

4. Customize field display according to the content model.AnQi CMS supports flexible content model custom fields. You can control the display based on whether these custom fields exist or on their values:

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

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

Enhance judgment ability with the filter.

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

  • |lengthFilter: Check 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 we judge the length of the article introduction, if it exceeds 50 characters, it will be truncated and display the 'Read More' link.

  • |containFilter: Determine if a string contains a specific substring.When you need to check if a string variable contains a specific keyword,|containFilters are very useful:

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

    This example simply checks if the contact phone number contains '888' and uses it to determine whether to display as VIP customer service.

  • |dumpFilter: Auxiliary debuggingDuring development, if the condition judgment does not work as expected,|dumpThe filter is a very useful debugging tool that can print out the structure, type, and value of variables: “`twig {{ archive|dump }} {% if debug_mode %} {# Assume there is a debug_mode variable #}

    <pre>{{ archive
    

Related articles

How does the comment function of AnQi CMS display comment lists and reply levels?

AnQiCMS (AnQiCMS) as an efficient and flexible content management system, provides rich content display capabilities while also offering a comprehensive comment function for user interaction.Understand how to effectively display a comment list, especially in handling multi-level replies, which is crucial for enhancing the user engagement and content depth of a website. ### AnQiCMS Comment Function Implementation Basics Commenting functionality is an important part of website content interaction in AnQiCMS.The system is not only built-in with support for comments on articles, products, and other content

2025-11-08

How to add and display friendship links on the Anqi CMS website?

In website operation, friendship links play an indispensable role.They not only help to improve the search engine ranking (SEO) of a website, but also bring potential traffic and improve the user experience, allowing visitors to get more information through related websites.AnQiCMS (AnQiCMS) understands this and therefore provides an intuitive and convenient friend link management feature, allowing you to easily add, manage, and display these important external connections.This article will introduce in detail how to add friend links in the Anqi CMS background, as well as how to flexibly display them on the website's front-end template

2025-11-08

How to display and manage the website message form of AnQi CMS and customize fields?

The website message form is an important link between users and the website, it not only helps us collect valuable opinions and suggestions, but also lays the foundation for various interactive functions such as user consultation and service reservation.AnQi CMS is well-versed in this, providing website operators with a straightforward, efficient, and highly customizable feedback form solution, making it exceptionally simple to manage and customize form fields.### Easily build the frontend presentation of the message form In Anqi CMS, to display the message form on the website page, you do not need to write complex backend logic, just insert the specific tags in the template file

2025-11-08

How to retrieve and display the document list under a specified Tag in AnQi CMS?

AnQiCMS (AnQiCMS) offers great convenience to website operators with its flexible content management and powerful template engine.In daily content operation, we often need to aggregate and display lists of related documents based on specific tags (Tag), such as 'Hot Topics', 'Technical Tips', or 'Product Reviews' and so on.This not only helps users quickly find the content they are interested in, but also effectively improves the internal link structure of the website, which is very beneficial for SEO.This article will delve into how to retrieve and display a list of documents under a specified tag in AnQiCMS

2025-11-08

How to perform a loop (for) in Anqi CMS template to display list data?

When building a website page, we often need to display various list data, such as the latest articles, product categories, navigation menus, or comment details.The template system of AnQiCMS provides us with a powerful and flexible loop traversal function, making the display of dynamic lists very simple.The template syntax of AnQi CMS borrows from the Django template engine, so users familiar with this syntax will feel very close.It uses the `for` loop label to iterate over the data collection and display each item one by one.###

2025-11-08

How to format a timestamp into a readable date and time format and display it in AnQi CMS?

In website content operations, the presentation of time is often ignored, but it is an important detail for improving user experience and content professionalism.The original timestamp number lacks meaning for ordinary users. Formatting it into a clear and easy-to-read date and time format makes the content more appealing.AnQi CMS knows this, providing a simple and powerful way to handle such needs.### Understanding the timestamp in AnQi CMS In AnQi CMS, whether it is the publication time (`CreatedTime`) or the update time (`UpdatedTime`)

2025-11-08

Does AnQi CMS support the automatic conversion of uploaded images to WebP format for optimized display?

In the era where content is king, the loading speed of website images directly affects user experience and search engine optimization (SEO) performance.Efficient image management and optimization strategies are crucial for any website committed to providing high-quality content services.Many website operators are actively seeking solutions that can automatically optimize images, especially those converted to WebP format.So, for those who are using or considering using AnQiCMS, does this system support automatic conversion of images to WebP format after upload to optimize display?The answer is affirmative

2025-11-08

How to set up automatic image compression in Anqi CMS to speed up page loading?

Optimize images, speed up the website: AnqiCMS Automatic Compression Settings Guide Website access speed is one of the key factors in user experience and an important consideration for search engine optimization (SEO).And large images are often the culprit that slows down website loading speed.Fortunately, AnqiCMS, as a fully functional content management system, is built with a series of powerful image optimization features, which help us easily deal with this issue, while keeping the website smooth in providing rich visual content.Today, we will take a detailed look at how to use AnqiCMS

2025-11-08