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

Calendar 👁️ 88

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.

Related articles

How to use the `if` tag in AnQiCMS templates to determine if a variable is empty, exists, or has a specific value?

In AnQiCMS template development, the `if` tag is the core tool for building dynamic page content.It allows us to flexibly control the display of content based on different conditions, thereby providing users with a more intelligent and personalized browsing experience.Whether you want to judge whether a data exists, whether it is empty, or hope to adjust the layout according to a specific value, the `if` tag can help you easily achieve it.AnQiCMS's template engine syntax is very similar to the Django template engine, therefore, developers familiar with this syntax will feel very亲切。`if`

2025-11-09

How to implement multi-condition logical judgment with the `if` tag in AnQiCMS template (OR/&&, AND/||, NOT/!)?

In AnQiCMS template development, mastering conditional logic judgment is the key to building dynamic and intelligent web pages.Among them, the `if` tag is the core of controlling content display, not only supporting simple boolean judgments, but also being able to flexibly implement logical combinations of multiple conditions, such as "and" (`&&`), "or" (`||`), and "not" (`!`)`etc. Understanding and skillfully using these logical operators can help us control the display and hiding of template elements more finely, thereby creating a more interactive and customizable user experience.### Basic Conditional Judgment: `if`

2025-11-09

How does the `yesno` filter combine with the data list in AnQiCMS templates to display the specific status of each piece of data?

During the process of building a website with AnQiCMS, we often need to display various data on the front-end page, which often has different states.For example, is an article published or a draft, a product listed or not, or is a user active or not.How to clearly and intuitively present these states to the user while keeping the template code concise and readable is a common concern for content operations and template developers.Today, let's delve into a very practical tool in AnQiCMS——the `yesno` filter

2025-11-09

In AnQiCMS template, can the `yesno` filter determine the true or false state of a numeric or string variable?

In AnQiCMS template development, in order to better control the display logic of content, we often need to judge the 'true or false' status of a variable.This is a very practical tool, the `yesno` filter.It can help us output different texts in a concise way based on the status of variables, and it can even handle numeric and string type variables.The `yesno` filter is designed to provide a straightforward way to handle ternary states: yes, no, and uncertain (or no value).The basic working principle is to parse the input variable into a boolean value (true or false)

2025-11-09

How to use the `not` operator to reverse conditional judgments in AnQiCMS templates?

The AnQiCMS template system is renowned for its flexibility and efficiency, drawing inspiration from Django's template engine syntax, making content presentation and logical control intuitive.In template development, we often need to display or hide content based on different conditions, at this point, mastering the various usages of conditional judgment is particularly important.Today, let's talk about how to cleverly use the `not` operator in AnQiCMS templates to reverse condition judgments, making your page logic clearer and more flexible.What is the `not` operator?

2025-11-09

The `in` operator in the AnQiCMS template's `if` statement, how to judge whether an element exists in an array or set?

When developing the AnQiCMS website template, we often need to dynamically display or hide content based on certain conditions.A common requirement is to determine whether an element exists within a dataset, such as checking if a user has a specific role or if the current article has a specific tag.AnQiCMS's template engine provides a concise and powerful `in` operator that can easily solve such problems. ### Core Function Explanation: What is the `in` operator?The design inspiration of AnQiCMS template engine comes from Django

2025-11-09

How to avoid excessive nesting of `if` statements in AnQiCMS templates to improve code readability?

In AnQiCMS template development, we often encounter situations where we need to display different content based on different conditions.Newcomers may tend to use the `{% if condition %}` statement extensively. As the project requirements grow, these conditional judgments become nested layer by layer, which quickly makes the template difficult to read, maintain, and even hides potential logical errors.Code readability once reduced, not only will the development efficiency be affected, but the future feature iteration and problem troubleshooting will also become extremely difficult.Fortunate is that AnQiCMS is based on Go language Django-like

2025-11-09

How to set default display content for possibly empty variables in the `default` filter of AnQiCMS templates?

In Anqi CMS template design, we often encounter situations where variable values may be empty.For example, an article may not have a thumbnail set or a product field may be temporarily unfilled.If the template directly displays these empty values, ugly blank spaces will appear on the page, affecting user experience, and may even confuse visitors.To solve this problem, Anqi CMS provides a very practical filter mechanism, where the `default` filter is the key tool to ensure the continuity of content display.### `default` Filter

2025-11-09