How to perform conditional judgments (if/elif/else) in Anqi CMS template?

Calendar 👁️ 57

As an experienced CMS website operation personnel, I know that the flexibility of templates is crucial for efficient operation in daily content management.Especially conditional judgments, which allow us to intelligently control the display and hiding of content based on different data states and business logic, thus providing users with more accurate and personalized browsing experiences.The Anqi CMS template engine borrows the syntax style of Django, making the implementation of conditional judgments both powerful and easy to understand.

Basic structure of conditional judgment in Anqi CMS template

In Anqi CMS template, conditional judgment is mainly realized throughif/elif(short for else if) andelsetags and implemented byendifThe tag ends. This structure is very similar to conditional statements in many programming languages, making it easy for operations personnel familiar with programming logic to quickly get started.

The structure of a basic conditional judgment statement is as follows:

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

If you need to handle multiple cases, you can introduceelifandelse:

{% if 条件1 %}
    <!-- 当条件1为真时显示的内容 -->
{% elif 条件2 %}
    <!-- 当条件1为假且条件2为真时显示的内容 -->
{% else %}
    <!-- 当所有条件都为假时显示的内容 -->
{% endif %}

AllifAll statements must end with{% endif %}tags must be correctly closed.

elements that make up the conditional expression

The core of conditional judgment lies in the construction of its expressions. Anqi CMS template supports various types of expressions, helping us precisely define judgment logic.

FirstlyComparison operatorWe can use common comparison operators to determine the relationship of values:

  • Equal:==(For example)archive.Id == 10)
  • Not equal:!=(For example)item.Id != 1)
  • Greater than:>(For example)simple.number > 42)
  • Less than:<(For example)simple.number < 42)
  • Greater than or equal to:>=(For example)simple.number >= 42)
  • Less than or equal to:<=(For example)simple.number <= 42)

Next isLogical operatorThey allow us to combine multiple conditions to form more complex judgments:

  • Logical AND:&&orand(For example)true && (true && (1 == 1 || false)))
  • Logical OR:||oror(For example)true || false)
  • Logical NOT:!ornot(For example)!true,not complex.post)

Additionally, there aremember operator inUsed to check if a value exists in a collection (such as an array, map):

  • For example5 in simple.intmapIt will judge5whether it existssimple.intmapin this collection.

The Anqi CMS template also handles certain values:Implicit true and false judgmentFor example, non-empty strings, non-zero numbers, non-empty lists or objects are usually consideredtrue; while empty strings, zero,nil(empty values) or empty lists are consideredfalseThis means we can directly go through{% if 变量名 %}to determine whether a variable has a value or is true.

The actual application of conditional judgment in templates

Conditional judgments are widely used in daily website operations, and the following are some common examples:

Content display or hide according to data status:We can decide whether to display relevant information based on the review status of the content, whether there are subcategories, or a specific attribute. For example, in the comment list, we can determine whether a comment is being reviewed:

{% if item.Status != 1 %}
    <span>此评论正在审核中</span>
{% else %}
    <span>{{item.Content}}</span>
{% endif %}

Or determine if a category has subcategories to decide whether to display the subcategory list or the document list under the category:

{% if item.HasChildren %}
    {% categoryList subCategories with parentId=item.Id %}
        <!-- 显示子分类 -->
    {% endcategoryList %}
{% else %}
    {% archiveList products with type="list" categoryId=item.Id limit="8" %}
        <!-- 显示该分类下的产品 -->
    {% endarchiveList %}

Handle special items in the list:When traversing a list in a loop, we often need to handle the first, last, or items that meet specific conditions differently. Byforloop.Counter(the current loop index, starting from 1) andforloop.Revcounter(Remaining loop count) and loop variables can be easily implemented:

{% for item in archives %}
    <li class="{% if forloop.Counter == 1 %}active{% endif %}">
        <a href="{{item.Link}}">{{item.Title}}</a>
        {% if forloop.Counter == 1 %}
            <span>这是列表的第一项!</span>
        {% endif %}
    </li>
{% empty %}
    <li>没有内容</li>
{% endfor %}

Handle optional data and placeholders:Most of the time, images, descriptions, or other fields may not be present for all content. Using conditional judgment can prevent the appearance of empty spaces or incorrect links:

{% if item.Thumb %}
    <img src="{{item.Thumb}}" alt="{{item.Title}}">
{% else %}
    <img src="/static/images/default-thumb.png" alt="默认缩略图">
{% endif %}

Again, in SEO optimization, the canonical link (Canonical URL) may only exist on specific pages:

{%- tdk canonical with name="CanonicalUrl" %}
{%- if canonical %}
    <link rel="canonical" href="{{canonical}}" />
{%- endif %}

Make a conditional judgment based on a custom field:If the content model defines custom fields, we can also judge based on the values of these fields. For example, a boolean custom field namedis_featuredis:

{% archiveDetail archive with name="is_featured" %}
{% if archive.is_featured %}
    <span class="featured-badge">推荐</span>
{% endif %}

Or in the loop output custom fields while excluding some fields:

{% categoryDetail extras with name="Extra" %}
{% for field in extras %}
    {% if field.Name != 'author' and field.Name != 'price' %}
        <div>{{field.Name}}:{{field.Value}}</div>
    {% endif %}
{% endfor %}

Nested and combined use

The conditional judgment statement in Anqi CMS template can be nested at any level and can be used with other template tags such asforCombining loops seamlessly. This powerful combination allows us to organize complex page logic in a highly structured way.For example, in a navigation list, determine if there is a sub-navigation, and further determine whether a product list needs to be displayed in the sub-navigation:

{% navList navList %}
    {%- for item in navList %}
        <li>
            <a href="{{ item.Link }}">{{item.Title}}</a>
            {%- if item.NavList %}
                <ul class="sub-menu">
                    {%- for inner in item.NavList %}
                        <li>
                            <a href="{{ inner.Link }}">{{inner.Title}}</a>
                            {% archiveList products with type="list" categoryId=inner.PageId limit="8" %}
                                {% if products %}
                                    <ul class="product-list">
                                        {% for product in products %}
                                            <li><a href="{{product.Link}}">{{product.Title}}</a></li>
                                        {% endfor %}
                                    </ul>
                                {% endif %}
                            {% endarchiveList %}
                        </li>
                    {% endfor %}
                </ul>
            {% endif %}
        </li>
    {% endfor %}
{% endnavList %}

This example shows how to nest in a loopforwithin a loopifDetermine andifAnother one nested inside the judgeforloop andifDetermine to achieve complex navigation structures.

Details and precautions

  • Tag closure:Make sure each{% if %}is matched with{% endif %}Otherwise, the template will not be parsed correctly.
  • Case Sensitive:Labels, variable names, and parameters in the template

Related articles

How to use the for loop in AnQiCMS template to traverse data and handle empty results with the empty tag?

## Master the data traversal and empty result handling in AnQiCMS templates: in-depth analysis of for loops and empty tags AnQiCMS, with its efficient and customizable features, has become the preferred content management system for many content operation teams and small and medium-sized enterprises.It is crucial for the flexibility of template language when building dynamic web pages.

2025-11-06

How to display the list of related documents in AnQiCMS template?

As a website operator who has been deeply involved in the CMS of security enterprises for many years, I know that effectively guiding users to discover more interesting content is crucial for enhancing user stickiness and the depth of website visits.Among them, the 'related document list' is undoubtedly one of the core functions to achieve this goal.It not only helps users conveniently explore more related topics, but also has a positive impact on the internal link structure of the website and SEO optimization.

2025-11-06

How to call the previous and next document links in AnQiCMS template?

As a senior CMS website operation personnel in an enterprise, I am well aware of the importance of content navigation for user experience and SEO.On a day when the content of the website is becoming richer and richer, how to guide users to smoothly browse related content is a key factor in enhancing user stickiness and reducing the bounce rate.Today, we will delve into how to cleverly call the links of the previous and next documents in the AnQiCMS template to optimize your website's content structure and user path.### Enhancing User Experience and SEO: Navigation of Previous and Next Documents in AnQiCMS Templates In the Content Management System

2025-11-06

How to obtain document detail data and display content in AnQiCMS template?

As an experienced security CMS website operator, I know that it is crucial to efficiently and accurately obtain and present document detail data in terms of content display.A well-crafted detail page not only meets users' in-depth information needs, but also effectively enhances the website's stickiness and search engine performance through optimizing content structure and user experience.In Anqi CMS, taking advantage of its flexible Django template engine syntax, obtaining and displaying document detail data is a direct and powerful process.

2025-11-06

How to format timestamp output in AnQiCMS template?

As a professional familiar with Anqi CMS and proficient in content operation, I know that accuracy and beauty in website content display are crucial.A clear and easy-to-read timestamp that not only improves user experience but also reflects the standardization of data display.Below, I will give you a detailed introduction on how to format timestamp output in AnQiCMS template.

2025-11-06

What are the common functions of filters in AnQiCMS templates (such as truncation, replacement)?

In AnQi CMS template design, filters play a vital role.As an experienced website operator, I know that skillfully using these tools can greatly enhance the quality of content presentation and user experience.The Anqicms template engine has adopted Django's syntax, allowing content creators and template developers to conveniently process and format output data, achieving rich display effects without delving into the backend code.

2025-11-06

How to implement string concatenation and array splitting in AnQiCMS templates?

AnQiCMS is an efficient and flexible content management system, whose powerful template engine provides a solid foundation for the dynamic display of website content.In daily content operation and template development, we often need to concatenate strings or split a string into multiple parts for processing according to specific rules.For example, building dynamic links, combining display information, or displaying the comma-separated tag list from the background data on the front end separately.Master the ability to concatenate strings and split arrays in AnQiCMS templates, which can greatly enhance the flexibility and expressiveness of the template

2025-11-06

How does AnQiCMS Markdown editor support math formulas and flowchart display?

As an experienced website operator proficient in the AnQi CMS content management system and with a keen perception of user needs, I am delighted to elaborate on how the AnQi CMS Markdown editor supports the display of mathematical formulas and flowcharts.Anqi CMS is committed to providing users with an efficient and flexible content management experience, and understands the importance of precise expression of mathematical formulas and clear presentation of flowcharts in specific fields (such as academic, technical blogs, or project management).

2025-11-06