How to build complex conditional display logic in the `if`, `elif`, `else` structure of AnQiCMS templates?

In AnQiCMS template design, dynamically displaying content is a key factor in enhancing website interactivity and user experience. When we need to decide what and how to display on the page based on specific data conditions,if/elif(else if abbreviation) andelseThese three conditional judgment tags are particularly important. They endow the template with flexible logical control capabilities, allowing our website to meet various complex display requirements.

AnQiCMS template engine's conditional judgment syntax is similar to many programming languages, very intuitive and easy to understand. All conditional judgment tags end with{%Start, with%}and are likeifThis structure usually requires a matching closing tag{% endif %}.

The foundation of conditional judgment:ifThe initial application of tags

The simplest conditional judgment is to useifThe label is used to check if a variable exists, is true, or meets a basic condition. For example, when displaying a list of articles, we may want to only show the image if the article has a thumbnail.

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

The meaning of this code is: ifarchive.Thumb(article thumbnail) exists, it will be displayed<img>Label. Ifarchive.Thumbis an empty string,nilorfalsethen the condition is not met,<img>the tag will not be rendered.

除了判断变量的真假值,我们还可以使用各种比较运算符来构建条件。AnQiCMS 支持常见的比较运算符,如 English==(等于), English!=(Not equal to),<(Less than),>(Greater than),<=(Less than or equal to),>=(Greater than or equal to). For example, we may need to display different content based on the article ID:

{% if archive.Id == 10 %}
    <p>这是 ID 为 10 的特别文章!</p>
{% endif %}

Build complex logic:elifandelseSkillful combination of

When faced with multiple mutually exclusive conditions, and need to execute different display logic based on different conditions,elifandelseCould be put to good use. They allow us to process complex business logic in a step-by-step manner, just like building with blocks.

Imagine a scenario, where we need to display different prompts based on the review's approval status:

{% if comment.Status == 1 %}
    <p>评论已通过审核。</p>
{% elif comment.Status == 0 %}
    <p>评论正在审核中,请耐心等待。</p>
{% else %}
    <p>评论状态未知或已被驳回。</p>
{% endif %}

In this example, ifcomment.StatusEqual to 1, show the first section of content; if it is not 1 but equal to 0, show the second section of content; if neither of the above conditions is met, then showelseThe default content of the part. This structure clearly handles various possibilities, making the page display more intelligent.

Understand the operators in conditional judgment more deeply

AnQiCMS Template Engine provides rich operators to help us build more refined conditional logic:

  • Comparison operatorsThe ones mentioned earlier:==,!=,<,>,<=,>=Can be used to compare numbers, strings, and even other comparable data types.
  • Logical operators:
    • and(Logical AND): The entire condition is true only when all subconditions are true.
    • or(Logical OR): When any of the subconditions is true, the entire condition is true.
    • not(Logical NOT): Reverses the truth value of a condition. For example, we want to display a special offer when the user logs in and is a VIP member:
    {% if user.IsLoggedIn and user.IsVIP %}
        <p>尊敬的 VIP 用户,您享有专属折扣!</p>
    {% endif %}
    
    English, if the article does not have pictures or videos, then display "Content missing":
    {% if not archive.HasImage and not archive.HasVideo %}
        <p>该文章内容可能不完整,请稍后查看。</p>
    {% endif %}
    
  • Member operator:
    • in(auto):Used to determine if a value exists in a list (array) or map. For example, you want to determine if a label exists in the tag list of an article:
    {% if "热门" in archive.Tags %}
        <span>此文章是热门推荐!</span>
    {% endif %}
    

The combination of conditional judgment with variables, functions, and filters

The strength of AnQiCMS templates lies in the fact that conditional judgments are not limited to simple variable values, but can also be cleverly combined with built-in variables, variables generated by tags, and various filters, thus realizing more complex dynamic display.

  1. Combine with loop variables.: Inforin the loop,forloop.CounterBuilt-in variables like this are often used for conditional statements. For example, you might want to apply a special style or mark to the first item in a list:
    
    {% for item in archives %}
        <li {% if forloop.Counter == 1 %}class="active-item"{% endif %}>
            <a href="{{item.Link}}">{{item.Title}}</a>
        </li>
    {% endfor %}
    
  2. Combine with variables generated by tags.:Many AnQiCMS tags (such aspagination/categoryList)Will generate variables containing specific status information. For example, in pagination navigation, determine whether the current page is the first page or the currently active page number:
    
    {% pagination pages with show="5" %}
        <a class="{% if pages.FirstPage.IsCurrent %}active{% endif %}" href="{{pages.FirstPage.Link}}">首页</a>
        {% for item in pages.Pages %}
            <a class="{% if item.IsCurrent %}current-page{% endif %}" href="{{item.Link}}">{{item.Name}}</a>
        {% endfor %}
    {% endpagination %}
    
  3. Combined with the filterEnglish: AnQiCMS provides various filters to handle and convert data.You can use the filtered result directly in the condition judgment.
    
    {% if archive.Description|length > 100 %}
        <p>{{archive.Description|truncatechars:100}} <a href="{{archive.Link}}">阅读更多</a></p>
    {% else %}
        <p>{{archive.Description}}</p>
    {% endif %}
    
    Here, we first uselengthFilter gets the description length, thentruncatecharsFilter truncates and displays.

Optimize template code: remove blank lines occupied by logic tags

When writing a template, you may noticeif/forThe logic tags will generate extra blank lines in the generated HTML, which may make the source code of the page less tidy. AnQiCMS provides a trick to solve this problem: add a dash in the start or end symbol of the tag-.

For example,{%- if 条件 %}It will remove the blank line before the tag.{% endif -%}It will remove the blank line after the tag. This is very useful when dealing with continuous logical blocks:

{# 假设这里有一行内容 #}
{%- if some_condition -%}
    <p>满足条件的内容</p>
{%- else -%}
    <p>不满足条件的内容</p>
{%- endif -%}
{# 这里是后续内容 #}

By this means, you can make the generated HTML more compact and reduce unnecessary whitespace.

Summary

if/elif/elseThe structure is the cornerstone of the complex conditional display logic implemented in the AnQiCMS template engine.Whether it is a simple true or false judgment, or multi-level conditional branches, or combining various operators, variables, functions, and filters, they can all help us precisely control the display of content.Proficiently using these conditional judgment tags will allow you to build a powerful and user-friendly AnQiCMS website more flexibly.


Common Questions and Answers (FAQ)

  1. How toifIn a statement, how to judge multiple conditions are met simultaneously or meet one?You can use logical operatorsand(satisfied simultaneously) oror(satisfied individually). For example,{% if condition1 and condition2 %}representingcondition1andcondition2the execution will take place only when all are true; whereas{% if condition1 or condition2 %}representingcondition1orcondition2the execution can take place when any one is true. You can also usenotTo negate a condition, for example,{% if not condition1 %}.

  2. Why is mine?ifThe statement did not take effect, or displayed content that should not be displayed?This usually has several reasons:

    • Variable name spelled incorrectly:AnQiCMS Template variables are case-sensitive, please check that the variable names match those provided in the documentation.
    • Incorrect conditional expressionFor example, an incorrect operator was used, or the logical combination is incorrect.
    • Data types do not match:Attempt to compare different types of data (such as the string '10' and the number 10) may result in unexpected outcomes. It is recommended to use it during debugging.{{ variable|dump }}Filter to view the actual type and value of variables.
    • Tags are not closed properly.All of theifLabels must all have correspondingendifLabel.
    • Empty ornilHandling of valuesIn AnQiCMS, it is used.nilor an empty string will be considered.false, but the specific behavior may vary depending on the context of the variable.
  3. {%- endif %}What is the role of the dash?This dash-(称为 Trim Whitespace,修剪空白) 用于控制模板渲染时是否移除标签前或标签后的空白字符(包括换行符)。{%-Remove leading spaces,-%}Represents the blank after removing the tag.Its main purpose is to make the generated HTML source code more compact, avoiding unnecessary blank lines, but it will not affect the actual display effect of the page in the browser (unless these blank spaces affect the layout).