How to construct complex conditional display logic in AnQiCMS templates using `if`, `elif`, and `else` structures?

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

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

The basics of conditional judgment:ifthe initial application of tags

the simplest conditional judgment is to useifLabels 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 show the image only when the article has a thumbnail:

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

The meaning of this code is: ifarchive.ThumbThe article thumbnail exists, it will be displayed<img>If the tagarchive.Thumbis an empty string,nilorfalseThen the condition does not hold,<img>The tag will not be rendered.

In addition to determining the truth value of variables, we can also use various comparison operators to construct conditions. AnQiCMS supports common comparison operators such as==(equals,)!=(not equal,)<(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:elifandelseThe clever combination

When faced with multiple mutually exclusive conditions, and need to execute different display logic based on different conditions,elifandelseThey can be put to good use. They allow us to process complex business logic in layers, like stacking building blocks.

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

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

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

Understand the operators in conditional judgments deeply.

AnQiCMS template engine provides rich operators to help us build more refined conditional logic:

  • Comparison operatorThe one mentioned earlier:==,!=,<,>,<=,>=Can be used to compare numbers, strings, and even other comparable data types.
  • Logical operator:
    • and(Logical AND): The entire condition is true only when all subconditions are true.
    • or(Logical OR): If any subcondition 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 %}
    
    Or, if the article has no images and no videos, then display "Content Missing":
    {% if not archive.HasImage and not archive.HasVideo %}
        <p>该文章内容可能不完整,请稍后查看。</p>
    {% endif %}
    
  • member operator:
    • in(Include): It is used to determine whether a value exists in a list (array) or a map (dictionary). For example, you want to check if a tag 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 to achieve more complex dynamic display.

  1. Combining with loop variablesInforthe loop,forloop.CounterBuilt-in variables are often used for conditional judgments. For example, you might want to apply special styles or marks to the first item in the list:
    
    {% for item in archives %}
        <li {% if forloop.Counter == 1 %}class="active-item"{% endif %}>
            <a href="{{item.Link}}">{{item.Title}}</a>
        </li>
    {% endfor %}
    
  2. Combining with variables generated by labels: Many AnQiCMS tags (such aspagination/categoryListVariables containing specific status information will be generated. 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 filters: AnQiCMS provides various filters to process and transform data.You can directly use the filtered result in the conditional judgment.For example, judge whether the length of a string is greater than a certain value:
    
    {% 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 use:lengthThe filter retrieves the length of the description and thentruncatecharsThe filter cuts and displays.

Optimize template code: remove blank lines occupied by logic tags

You may notice when writing a template,if/forLogic tags may cause extra blank lines in the generated HTML, which may make the page source code 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 条件 %}Will remove the blank line before the tag,{% endif -%}Will remove the blank line after the tag. This is very useful when processing consecutive logical blocks:

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

In this way, you can make the generated HTML more compact, reducing unnecessary whitespace.

Summary

if/elif/elseThe structure is the cornerstone of implementing complex conditional display logic 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 accurately control the display of content.Familiarly using these conditional judgment tags will enable you to build a powerful, user-friendly AnQiCMS website more flexibly.


Frequently Asked Questions (FAQ)

  1. How toifHow to judge multiple conditions in a statement, all at the same time or one of them?You can use logical operatorsand(Satisfied simultaneously) oror(Satisfied individually). For example,{% if condition1 and condition2 %}Indicatescondition1andcondition2It will execute only if all are true; whereas{% if condition1 or condition2 %}Indicatescondition1orcondition2It can execute if any one is true. You can also usenotNegate a certain condition, for example{% if not condition1 %}.

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

    • Variable name is spelled incorrectly: AnQiCMS template variables are case-sensitive, please carefully check if the variable name is consistent with the one provided in the documentation.
    • Error in conditional expressionFor example, an incorrect operator has been used, or the logical combination is incorrect.
    • Type mismatchTry comparing different types of data (such as the string '10' and the number 10) may result in unexpected results. It is recommended to use debugging when{{ variable|dump }}A filter to view the actual type and value of the variable.
    • The tag is not closed correctlyAll ofiftags must have correspondingendif.
    • Empty value ornilValue handlingIn AnQiCMS,nilor an empty string is considered to befalsebut the specific behavior may vary depending on the context of the variable.
  3. {%- endif %}What is the role of the dash inthis dash-(Called Trim Whitespace, trim whitespace) Used to control whether to remove whitespace before or after tags during template rendering (including newline characters).{%-indicating the removal of whitespace before the tag,-%}It represents the blank space after removing the tag. Its main purpose is to make the generated HTML source code more compact, avoid unnecessary blank lines, but it will not affect the actual display effect of the page in the browser unless these blanks affect the layout.