The conditional logic in the AnQi CMS template: flexible application{% if ... elif ... else ... %}Achieve multi-branch control

As an experienced website operations expert, I know that flexible and diverse website content display is crucial for user experience and operational efficiency.AnQiCMS (AnQiCMS) provides us with powerful content management capabilities with its efficient and customizable features.How to display different content based on different situations in template creation, and achieve fine-grained content operation?{% if ... elif ... else ... %}.

This set of tags allows us to execute different code blocks in templates based on specific conditions, making the website content dynamic and responsive.It is not only the foundation for personalized display, but also the key to improving user interaction and information delivery efficiency.

The foundation of conditional judgment:{% if ... else ... %}The 'yes' and 'no' of it

In the AnQi CMS template, the most basic conditional judgment is{% if 条件 %} ... {% endif %}. It's like a simple switch, when the 'condition' is true, it executesifandendifContent between the semicolons; if the condition is not met, this content will be ignored.

For example, we may want to display a welcome message after the user logs in, and a login prompt when not logged in:

{% if is_logged_in %}
    <p>欢迎回来,尊敬的用户!</p>
{% endif %}

If we need to provide an alternative when the condition is not met,{% else %}the label comes in handy:

{% if is_logged_in %}
    <p>欢迎回来,尊敬的用户!</p>
{% else %}
    <p>您好,请先<a href="/login">登录</a>或<a href="/register">注册</a>。</p>
{% endif %}

Here are theis_logged_inCan be a boolean variable passed from the backend to the template. The condition can be any expression that can be evaluated as true (true) or false (false).

Handle multiple conditional branches:{% elif ... %}The subtle art of:

When our content display logic is no longer just a simple 'yes' or 'no', but requires selectively displaying content based on multiple mutually exclusive conditions, {% elif ... %}It becomes an indispensable tool, which is the abbreviation of 'else if'. It allows us to have aifDefine a series of conditional branches in a statement, each of which is checked in turn if the previous condition is not met.

Imagine, we are building a news detail page, and we need to display different tags or styles based on the article's "recommended attributes" (Flag) to display different tags or styles:

{% archiveDetail current_archive %} {# 假设获取当前文章详情 #}
    <h1 class="article-title">{{ current_archive.Title }}</h1>

    {% if current_archive.Flag | contain:"h" %} {# 检查是否包含“头条”属性 #}
        <span class="badge badge-primary">头条</span>
    {% elif current_archive.Flag | contain:"f" %} {# 检查是否包含“幻灯”属性 #}
        <span class="badge badge-info">幻灯</span>
    {% elif current_archive.Flag | contain:"c" %} {# 检查是否包含“推荐”属性 #}
        <span class="badge badge-success">推荐</span>
    {% else %}
        <span class="badge badge-secondary">普通文章</span>
    {% endif %}

    <div class="article-content">{{ current_archive.Content | safe }}</div>
{% endarchiveDetail %}

In this example, the system will first check if the article is a "headline", and if so, it will display the "headline" tag and skip the subsequent judgment.If not, then continue to check whether it is a 'slide', and so on.ifandelifOnly when none of the conditions are met will the execution take place.elseContent within the block. The characteristic of sequential execution makeselifvery efficient and intuitive when handling priority or mutual exclusion conditions.

Deeply explore the mysteries of condition judgment.

Masterif/elif/elseThe basic usage is just the first step, to master the Anqi CMS template, we also need to understand some advanced details:

  1. The diversity of conditional expressions:In addition to direct variable judgments, we can also use various comparison operators in conditions (==equals,!=Not equal to,<Less than,>Greater than,<=Less than or equal to,>=Greater than or equal to) as well as logical operators (andand,oror,notnot). For example,{% if archive.Views > 100 and archive.CommentCount > 10 %}we can check both the number of visits and the number of comments at the same time.inThe operators are also very useful, for example,{% if item.Id in selected_ids %}to determine if a certain ID is in the given list.

  2. Judgment of 'true value' and 'false value':In the AnQi CMS template, some values are implicitly evaluated astrueorfalse:

    • non-zero numbers (e.g.,1,-5) are usuallytrue, zero (0) isfalse.
    • Non-empty string ("hello") and list (["a", "b"]) are usually true, empty string ("") and empty list ([]) isfalse.
    • Boolean valuetrueistrue,falseisfalse.
    • nilornothingusually indicatesfalse. This means you can simplify some judgments, such as{% if category.HasChildren %}willHasChildrenattribute oftruetakes effect immediately without writing{% if category.HasChildren == true %}.
  3. Nested conditions:To handle more complex logic,if/elif/elseSentences can be nested layer by layer. But remember, the purpose of the template is to display data, and complex logic should be processed as much as possible on the backend (controller) to maintain the clarity and maintainability of the template.

  4. Blank space control:In the template, conditional tags themselves may introduce unnecessary blank lines in the output HTML. To keep the output neat, you can use{%-and-%}Syntax to control the generation of whitespace. For example,{%- if condition %}it will remove the whitespace on the left side of the tag,{%- endif -%}it will remove the whitespace on both sides of the tag. This is very useful for generating compact HTML structures.

    {# 可能会产生空行 #}
    {% if article.is_hot %}
    <p>热门文章</p>
    {% endif %}
    
    
    {# 使用空白符控制,避免空行 #}
    {%- if article.is_hot -%}
    <p>热门文章</p>
    {%- endif -%}
    

Summary

In the Anq CMS template,{% if ... elif ... else ... %}Combinatorial tags, providing powerful dynamic content capabilities for website operators.Whether it is a simple yes or no choice, or a complex multi-branch judgment, they can all help us display the most appropriate and attractive content based on different conditions.By flexibly applying these conditional logic,配合好运算符和空白符控制,we can build high-quality websites with better user experience and lower maintenance costs.


Common Questions (FAQ)

Why is my{% if ... %}result different from what I expected?This is usually caused by improper use of variable type, value, or operator in the condition expression. Please check:

  • Does the variable exist or is it empty? nilValue, empty string, empty list, number0Is usually evaluated asfalse.
  • Does the data type match?For example,"10"(string) with10Numbers may not be equal in strict comparison.
  • Is the operator correct?Make sure to use the correct comparison operator (==,>) and logical operator (and,or,not).

2. When using{% if ... %}How to avoid extra blank lines in the output HTML when formatting statements?You can use whitespace to control syntax. Add a hyphen on the left or right side of the tag-For example,{%- if condition -%}This will remove the blank lines that the tag and its content generate on both sides. This is especially useful when generating compact HTML structures or handling inline elements.

**3.{% elif ... %}and `{%