How to use conditional judgment (if/else) tags to control content display logic in AnQiCMS templates?

In the development and maintenance of website templates, we often encounter the need to display or hide different content based on specific conditions.This dynamic content display logic is crucial for improving user experience, implementing personalized functions, and optimizing the website structure.if/elseThe tag is the core tool to achieve this goal.

The template engine syntax of Anqi CMS is similar to Django, which allows developers to use concise and intuitive tags to control the generation of page content.Through the clever use of conditional judgment, we can make the website content more intelligent and more closely aligned with the actual visiting context of users.

Master the basic conditional judgment syntax.

In the AnQi CMS template, conditional judgment tags are used in the following way:{% if ... %}and ends with{% endif %}The end. This is the basic usage, when the condition inside the brackets is met (i.e., true), the content inside will be displayed; otherwise, it will not.

For example, we may need to check if a variable exists or is empty. Suppose we are displaying the details of an article and we only want to show it when the article title exists:

{% if archive.Title %}
    <h1>{{ archive.Title }}</h1>
{% endif %}

Here,archive.TitleRepresents the article title. If the article title has a value, this<h1>the tags and title content will appear on the page; if the title is empty, then the whole<h1>The label and its content will not be rendered.

Branch introduced for 'else':if-else

很多时候,当一个条件不满足时,我们需要提供一个替代方案来显示不同的内容。这时,else标签就派上了用场。它与ifTag combination to form a logical branch of two choices:

{% if archive.Thumb %}
    <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}">
{% else %}
    <img src="/static/images/default-thumb.jpg" alt="默认缩略图">
{% endif %}

In this example, if the article has a thumbnail (archive.Thumb), and it will display the thumbnail of the article itself; if not, it will display a preset default thumbnail.This ensures the integrity of the page layout, avoiding blank or style issues due to missing images.

Handle multiple conditions:if-elif-else

When we need to handle more than two conditions, not just a couple of mutually exclusive cases,elif(Else if abbreviation) the label becomes particularly important.It allows us to check a series of conditions in order, until the first condition that meets the requirements is found and its corresponding code block is executed.ifandelifthe conditions are not met, the last oneelseblock (if it exists) will be executed as the default case.

For example, in the list of articles, we may want to sort according to the article's 'recommended attributes' (Flag) to display different marks:

{% if item.Flag == 'h' %}
    <span class="flag-hot">热点</span>
{% elif item.Flag == 'c' %}
    <span class="flag-recommend">推荐</span>
{% elif item.Flag == 'f' %}
    <span class="flag-slide">幻灯</span>
{% else %}
    <!-- 其他文章不显示特殊标记 -->
{% endif %}

Here,item.FlagIt indicates the recommended attributes of the article (such as fromarchiveListTagged article list items). The system will check in sequence whether the article is a hot topic, recommended, or slide, and display the corresponding tag. If none of these apply, no special marker will be displayed.

Flexible application scenarios of conditional judgment

The powerful aspect of conditional judgment lies in its ability to deeply integrate with various tags and data models provided by Safe CMS, achieving extremely flexible content control.

  • Prompt when the list content is empty:When usingarchiveListorcategoryListWhen obtaining data lists with tags such as 'auto', if the list is empty, we can use the statement to judge the length of the list variable and display the prompt 'No content' instead of leaving it blank. For example,ifthe statement to judge the length of the list variable and display the prompt 'No content' instead of leaving it blank. For example,{% if archives|length > 0 %}Then traverse the list,{% else %} <div>暂无相关文章</div> {% endif %}.

  • The current selected state of the navigation menu:When building the navigation menu,navListTag returnsitem.IsCurrentThe attribute is very useful. We can use it to determine whether the current navigation item is the page the user is visiting, and add aactiveclass to highlight:

    <li {% if item.IsCurrent %}class="active"{% endif %}>
        <a href="{{ item.Link }}">{{ item.Title }}</a>
    </li>
    
  • Control function display according to system settings:Anqi CMS'ssystemTags can obtain the global configuration information of the website. For example, we can determine whether the website is in a closed state and display the corresponding prompt page:

    {% system siteStatus with name="SiteStatus" %}
    {% if siteStatus == 0 %} {# 假设0代表关闭状态 #}
        {% system closeTips with name="SiteCloseTips" %}
        <div class="site-closed-message">
            {{ closeTips|safe }}
        </div>
    {% else %}
        <!-- 正常网站内容 -->
    {% endif %}
    

    Here are some points to note, the documenthelp-setting-system.mdin网站状态The description is当你选择为闭站状态下,用户将只会看到闭站提示信息。, which means that the shutdown logic has been handled at the system level, and the template level may be more used for judging other custom system parameters.

  • Custom field personalized display:PassarchiveDetailorcategoryDetailThe custom field obtained can be displayed according to its existence or specific value. For example, if the product model has a custom field calledPrice:

    {% archiveDetail productPrice with name="Price" %}
    {% if productPrice and productPrice > 0 %}
        <p>价格: {{ productPrice }} 元</p>
    {% else %}
        <p>价格: 询价</p>
    {% endif %}
    
  • Process the availability of pagination links:InpaginationThe pagination object returned by the tag,pages.PrevPageandpages.NextPageCan be used to determine if there is a previous page or next page, thereby deciding whether to display the corresponding navigation buttons.

    {% if pages.PrevPage %}
        <a href="{{ pages.PrevPage.Link }}">上一页</a>
    {% else %}
        <span class="disabled">上一页</span>
    {% endif %}
    

Write the notes when writing conditional judgments

There are some tips that can help us write clearer and more efficient code when writing conditional judgments:

  1. Be clear about the end tags:Every one{% if %}All of them must have corresponding ones{% endif %}。If usedeliforelse,they must beifandendifbetween.
  2. used with logical operators:You can useand/or/notThese logical operators can be used to combine more complex conditions, such as{% if user.IsLoggedIn and user.IsAdmin %}.
  3. variable existence judgment:Simply place the variable name inifthe statement, and you can judge whether the variable exists and is not empty (for strings, numbers, lists, etc.). For example,{% if archive.Content %}it will bearchive.Contenttrue when it is not empty.
  4. Precise comparison:You can use==(equals,)!=(not equal to,)<(less than,)>(greater than,)<=(Less than or equal to),>=(Greater than or equal to) etc. comparison operators.
  5. Remove extra spaces:Use within conditional tags{%-or-%}Can remove whitespace before or after the line containing the tag, which is very useful for generating neat HTML code, especially when extra newline characters may be introduced by loops or conditional statements. For example:{%- if condition -%}.

Through flexible use of the conditional tags in the security CMS template, we can create websites that are responsive, feature-rich, and have more intelligent content display.This not only enhances the professionalism of the website, but also brings visitors a better browsing experience.


Common Questions (FAQ)

1. I can use which types of operators in conditional judgments?

You can use various operators in the conditional judgments of the AnQi CMS. In addition to the equality operator mentioned earlier,==)、不相等(!=)、大于(>)、小于(<)等比较运算符外,您还可以使用逻辑运算符,如and(Logical AND),or(Logical OR) andnot(逻辑非),来组合或否定条件。例如,“English”}]{% if item.Views > 100 and item.Flag == 'h' %}. Moreover, you can even perform simple arithmetic operations in conditional judgments, such as{% if item.Price * item.Quantity > 500 %}.

2. How to apply different styles to different items based on conditions in a loop?

InforIn the loop, you can use conditional judgment combined with the properties of the loop variable to dynamically apply styles. For example,forloop.CounterCan retrieve the current loop index (starting from 1),forloop.RevcounterCan get the remaining loop count. You can add the first item in the loop like thisactiveClass:

{% for item in archives %}
    <div class="list-item {% if forloop.Counter == 1 %}active{% endif %}">
        {{ item.Title }}
    </div>
{% endfor %}

You can also combine the attributes of the data itself (such asitem.IsCurrentoritem.Status)to determine, based on different values, to apply different CSS classes.

3. What happens if the variable referenced in the conditional judgment does not exist or is empty?

In the Auto CMS template, when you areifWhen a variable that does not exist or an existing variable with an empty value (such as an empty string, number 0, nil, an empty list, or an empty object) is referenced directly in a statement, the condition will be evaluated as false.falseThis is typically a convenient feature as it allows you to safely check for the existence of data without causing template rendering errors. For example,{% if archive.Author %}only