How does the Anqi CMS template support `if`, `elif`, `else` logical judgments?

Calendar 👁️ 61

In Anqi CMS template design, in order to achieve dynamic content display and complex layout control, conditional logic judgment is an indispensable part. As a website operator, I know the importance of flexible applicationif/elif/elseLogical judgment tags that allow us to present a variety of page content based on different data states or business needs, thereby enhancing user experience and website interaction.

The AnQi CMS template engine supports syntax similar to the Django template engine, which allows users familiar with other mainstream CMS template languages to quickly get started. Conditional tags are used.{% ... %}forms definition, and they must appear in pairs, that is, eachiftags must have correspondingendiftags to end a conditional block.

The basis of conditional judgment in Anqi CMS templates

In Anqi CMS template, the most basic conditional judgment statement isiftag. It is used to determine whether the value of an expression is true. If the result of the expression calculation is true(true), thenifThe code block inside the tag will be executed and rendered. For example, when we want to display content based on whether a variable exists or has a specific value,ifthe tag becomes very useful.

A simpleifJudgment can be constructed like this:

{% if variable_name %}
    <!-- 当 variable_name 为真时显示的内容 -->
{% endif %}

Herevariable_nameIt can be any data directly passed from the backend to the template, for examplearchive.Id/item.TitleAnd in the context of AnQi CMS templates, numeric variables are true if not zero, strings are true if not empty, lists or arrays are true if not empty, andnilValues such as empty, empty strings, or zero are usually considered false. We can even directly evaluate boolean variables.

IntroductionelsePerform a yes/no decision

In many scenarios, we not only need to define the logic to be executed when a condition is true, but also need to provide an alternative when the condition is false. At this point,elsethe label comes into play.ifwithelseCombine to form a binary branch option, ensuring that no matter the condition, part of the content will always be rendered.

The structure is as follows:

{% if condition_expression %}
    <!-- 条件为真时显示的内容 -->
{% else %}
    <!-- 条件为假时显示的内容 -->
{% endif %}

For example, we can determine whether a document has a thumbnail, and if not, display a default placeholder:

{% if item.Thumb %}
    <img src="{{ item.Thumb }}" alt="{{ item.Title }}" />
{% else %}
    <img src="/static/images/default_thumb.jpg" alt="默认图片" />
{% endif %}

UseelifHandle multiple conditional branches

When faced with multiple mutually exclusive conditions and needing to check them one by one,elifthe (else if abbreviation) tag provides an elegant solution.elifallows us to initializeifAfter a condition is not met, continue checking other conditions until a true condition is found. If allifandelifconditions are false, then the optionalelseblock (if it exists) will be executed.

The typical structure of a multi-condition judgment is as follows:

{% if first_condition %}
    <!-- 当第一个条件为真时执行 -->
{% elif second_condition %}
    <!-- 当第一个条件为假且第二个条件为真时执行 -->
{% elif third_condition %}
    <!-- 当前两个条件为假且第三个条件为真时执行 -->
{% else %}
    <!-- 所有条件都为假时执行 -->
{% endif %}

A practical example may be to display different styles or markers in a loop based on the recommended properties of the document(Flag) to display different styles or markers.flagThe property supports multiple values, such ash(Headline),cRecommended, etc.

{% for item in archives %}
    {% if item.Flag == 'h' %}
        <span class="badge badge-hot">头条</span>
    {% elif item.Flag == 'c' %}
        <span class="badge badge-recommend">推荐</span>
    {% else %}
        <!-- 没有特定推荐属性时不做处理或显示默认 -->
    {% endif %}
    <a href="{{item.Link}}">{{item.Title}}</a>
{% endfor %}

Logical AND comparison operation in conditional judgment

The AnQi CMS template engine supports the use of various logical and comparison operators in conditional expressions, which greatly enhances the flexibility of conditional judgments. Common operators include:

  • Comparison operator:==(equals,)!=(not equal,)<(less than,)>(greater than,)<=(less than or equal to),>=(greater than or equal to).
  • Logical operator:and(logical AND),or(logical OR),not(logical NOT).
  • member operator:in(Check if the element is in the set).

These operators can be combined to form complex judgment logic. For example, we can determine whether a numerical variable is within a specific range, or whether a string is included in a certain list:

{% if simple.number > 10 and simple.number < 100 %}
    <p>数字在10到100之间。</p>
{% endif %}

{% if item.Status == 1 or item.Status == 2 %}
    <p>状态为活跃或待审核。</p>
{% endif %}

{% if not archive.IsPublished %}
    <p>此文档尚未发布。</p>
{% endif %}

{% if 'keyword' in article.Keywords %}
    <p>文章关键词中包含'keyword'。</p>
{% endif %}

The combination of conditional judgment and loop usage

Conditional judgment tag andforThe combination of loop tags is a common pattern used in Anqi CMS templates to achieve dynamic content display. For example, when iterating over a list, we can according toforloop.Counter(The current loop index, starting from 1) to handle elements at specific positions:

{% for item in archives %}
    <li class="{% if forloop.Counter == 1 %}first-item{% endif %}">
        <a href="{{item.Link}}">{{item.Title}}</a>
    </li>
{% endfor %}

This usage is very suitable for adding unique styles or behaviors to the first, last, or specific position elements in a list.

Optimize the conditional logic in the template code.

In order to maintain the neatness and readability of the template code, Anqi CMS also provides a method to remove the empty lines occupied by logical tags. Inif/elif/else/endifusing before or after the tags.-The symbol can eliminate the extra blank lines generated by the tags themselves, thus generating a more compact HTML output, which is a useful detail for operators who pursue ultimate page performance.

{%- if condition -%}
    <p>内容紧凑地显示。</p>
{%- else -%}
    <p>另一段紧凑内容。</p>
{%- endif -%}

In summary, within the AnQi CMS template,if/elif/elseLogic judgment tags provide powerful control over content display.By flexibly using these tags, combined with various operators, website operators can easily achieve personalized and dynamic display of content, whether based on user identity, data status, or other business logic, and can build responsive and excellent user experience pages.This has enhanced the functionality of the website and also laid a solid foundation for refined operation and content marketing strategies.


Frequently Asked Questions (FAQ)

1. If I forget toifadd at the end of the statement,endifWhat will happen to the tags?

In the AnQi CMS template engine, all conditional judgment tags (such asif,elif,else) must end withendifExplicitly close the tag. If you miss itendif, the template engine will report an error during parsing, causing the page to fail to render normally, and it will usually throw an error such as 'unclosed tag'.Therefore, be sure to ensure that each conditional block has the correct closing tag.

2. Can IifNested other statements insideifIs this statement?

Yes, the template engine of Anqi CMS fully supportsifNested statements. This means you can put one in anotherif/eliforelseInside the block, define a new conditional judgment logic. This nested mechanism allows you to build very complex and fine-grained page logic to meet the needs of multi-level business requirements. For example:

{% if user.IsLoggedIn %}
    <p>欢迎回来,{{ user.Name }}!</p>
    {% if user.IsVIP %}
        <p>您是尊贵的VIP用户,享有特别优惠。</p>
    {% else %}
        <p>升级VIP,享受更多特权!</p>
    {% endif %}
{% else %}
    <p>请登录或注册。</p>
{% endif %}

3. How to check if a variable is empty (nil) or undefined?

In AnQi CMS templates, you can directly useif variable_nameto check if a variable is empty or undefined. Ifvariable_namehas a value ofnil, an empty string, a number0and Booleanfalseor an empty array/list, it will be evaluated asfalsethus triggeringelseblock (if it exists). You can also explicitly useif variable_name == nilCheck it, but this is usually unnecessary because the template engine's truthy evaluation is sufficient. For a stricter check of empty strings, you can useif variable_name == "".

Related articles

How to implement and display pagination navigation on list pages (such as article lists, search results)?

As an experienced CMS website operations personnel for an Internet security company, I know that the details of content presentation are crucial for user experience and website SEO.Page navigation is one of the fundamental and key components, which not only helps users efficiently browse a large amount of content, but also allows search engines to better crawl and index website information.Today, I will elaborate on how to elegantly display pagination navigation on the list page of AnQi CMS, such as article lists, search result pages, etc.### Overview of Pagination Mechanism in AnQi CMS Implementing pagination functionality in AnQi CMS is intuitive and efficient

2025-11-06

How to retrieve and display the list of友情链接 configured in the background?

As an experienced CMS website operation personnel, I fully understand the importance of efficient content management and front-end display for the success of the website.Friend links are an important part of a website's external cooperation and SEO optimization, and their convenient acquisition and display methods are an indispensable part of daily operation.Now, I will elaborate on how to obtain and display the list of友情链接 links configured in the AnQiCMS admin panel.### AnQi CMS: Efficient management and display of the background friendship link list Friendship links, as an important part of website external link construction

2025-11-06

How to embed and display a user留言表单in a template?

As a website operator who deeply understands the operation of AnQiCMS, I fully understand the importance of providing user interaction channels on the website.The user feedback form is a key tool for collecting feedback, answering questions, and building relationships with users.In AnQiCMS, embedding and displaying a comment form through its flexible template engine is a direct and highly customizable process.This article will detail how to implement this feature in the AnQiCMS template.

2025-11-06

How to retrieve and display the website's comment list, including multi-level replies?

As a website content expert who deeply understands the operation of Anqi CMS, I am well aware of the readers' needs for interactivity and information transparency.The comment feature is an important way for users to participate in website content construction and express their opinions, and multi-level replies can effectively promote in-depth communication between users.AnQi CMS provides us with a powerful and flexible comment management mechanism, making it efficient and convenient to retrieve and display comment lists, including multi-level replies.

2025-11-06

How to use a `for` loop to iterate over data and handle `empty` data situations?

As an experienced CMS website operations personnel, I fully understand the importance of content in attracting and retaining users.Dynamic, responsive website content display is the key to improving user experience, and effectively handling data sets, especially when the data may be empty, is a basic skill in operation work.AnQiCMS (AnQiCMS) powerful template engine provides us with flexible tools to achieve these goals, where the `for` loop tag and its `empty` block are our powerful assistants for content display.

2025-11-06

How to format a timestamp from a database into a readable date and time string?

As an experienced CMS website operation personnel of AnQi, I know that the content of the website should not only be rich, but also presented in a user-friendly manner.Time information is an important part of the content, but the timestamps (Unix timestamps) stored in the database are often just a string of numbers, which can be confusing to display directly.Therefore, formatting these timestamps into easily readable date and time strings is a key step in enhancing user experience and increasing content readability.

2025-11-06

How to define a temporary variable and perform assignment operations in a template?

Hello! As an experienced AnQi CMS website operator, I am very happy to be able to explain in detail how to define and assign temporary variables in AnQi CMS templates.This is crucial for achieving the flexibility, readability, and maintainability of templates, enabling us to organize and display website content more efficiently.In the Anqi CMS template system, we often encounter scenarios where we need to store data, calculate results, or prepare content for specific components locally.To meet these requirements, Anqi CMS provides a concise and powerful variable definition mechanism, mainly realized through two tags

2025-11-06

What are the different roles of the three auxiliary tags `include`, `extends`, and `macro` in template structure organization?

As an experienced CMS website operation personnel of AnQi, I am well aware of the importance of a clear and efficient template structure for content management and website maintenance.In AnQi CMS, the template engine provides various auxiliary tags to help us better organize and reuse template code, among which `include`, `extends`, and `macro` are the three great tools for building a flexible template architecture.They each have different responsibilities, but together they serve to enhance the maintainability and development efficiency of the template.### Modular content reuse

2025-11-06