How to use `if-else` conditional tags to control the display logic of content in AnQiCMS templates?

Calendar 👁️ 89

In AnQiCMS template, make good use ofif-elseConditional judgment tags make content display more intelligent

In website content operation, we often need to display different content or styles based on different conditions.For example, when the article list is empty, display "No content", when an article is recommended, add the "HOT" mark, or add a special style for the first item in the loop.The template system of AnQiCMS (AnQiCMS) fully considers these needs, draws on the powerful syntax of the Django template engine, and provides flexibleif-elseConditional judgment tags help us easily achieve these dynamic content display logic.

if-elseTag syntax basics

The AnQi CMS template includesif-elseConditional tags are defined using single curly braces and percent signs and must appear in pairs to{% endif %}end. Its basic structure is very intuitive:

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

If we need to display another part of the content when the condition is not met, we can useelseTags:

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

When there are multiple conditions that need to be judged in order,elif(else if abbreviation) the tag comes into play:

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

Here, the 'condition' can be a boolean value of a variable, a comparison expression between variables, or a complex expression containing logical operators.

Flexible and variable conditional judgment application

if-elseThe power of tags lies in their ability to adapt to various complex business logic, making our content display more intelligent and dynamic.

  1. Determine if the content exists or is emptyThis is one of the most common application scenarios. For example, when we need to display a document list, if the list is empty, we prompt the user with 'No content available'.In Anqi CMS, document lists are usually accessed byarchiveListorcategoryListLabel retrieval.

    {% archiveList archives with type="list" categoryId="1" limit="10" %}
        {% if archives %} {# 判断 archives 变量是否包含内容 #}
            <ul>
                {% for item in archives %}
                    <li><a href="{{item.Link}}">{{item.Title}}</a></li>
                {% endfor %}
            </ul>
        {% else %}
            <p>该分类下暂无任何文档内容。</p>
        {% endif %}
    {% endarchiveList %}
    

    Similarly, inforIn the loop, we can also make use ofemptya clause to achieve the same purpose, which is a more concise way:

    {% for item in archives %}
        <li><a href="{{item.Link}}">{{item.Title}}</a></li>
    {% empty %}
        <p>该列表没有任何内容。</p>
    {% endfor %}
    
  2. to display based on data attributesWe often need to decide whether to display a specific element or different content based on some attribute of the content.

    • Determine if the image exists: If the document has a thumbnail (item.ThumbIf so, an image will be displayed; otherwise, a placeholder may be displayed.

      {% if item.Thumb %}
          <img src="{{item.Thumb}}" alt="{{item.Title}}">
      {% else %}
          <img src="/static/images/placeholder.png" alt="无图片">
      {% endif %}
      
    • Tags are displayed based on recommended attributes Assuming a document is marked as "Top Recommendation" (flag="h"We can add a "HOT" tag next to its title.

      {% if item.Flag and item.Flag|contain:"h" %} {# 假设 Flag 包含多个属性,使用 contain 过滤器判断 #}
          <h3>{{item.Title}} <span>HOT</span></h3>
      {% else %}
          <h3>{{item.Title}}</h3>
      {% endif %}
      
  3. Special handling in the loopInforthe loop,forloopThe variable provides information about the current loop state, combinedifLabels, can handle special processing of specific elements in the loop.

    • Add special style to the first item:

      {% for item in archives %}
          <li class="{% if forloop.Counter == 1 %}active{% endif %}">
              <a href="{{item.Link}}">{{item.Title}}</a>
          </li>
      {% endfor %}
      
    • Handle odd and even row styles:

      {% for item in archives %}
          <li class="{% if forloop.Counter is odd %}odd-row{% else %}even-row{% endif %}">
              {{item.Title}}
          </li>
      {% endfor %}
      
  4. Distinguish content on different pagesWhen developing templates, it may be necessary to display different block content on different pages (such as the home page, category page, and detail page).Although it can be implemented through template inheritance, it may also be controlled by judging the current page type in the same template file at times.For example, determine whether the current page is of a specific category:

    {% categoryDetail currentCategory %}
    {% if currentCategory.Id == 10 %} {# 假设当前页面是ID为10的分类页 #}
        <!-- 显示分类ID为10的专属内容 -->
    {% else %}
        <!-- 显示其他分类的通用内容 -->
    {% endif %}
    
  5. Handle complex logic and custom fieldsOur AQi CMS allows us to customize fields for the content model. The data of these custom fields can also be used toif-elsemake conditional judgments. For example, custom fields can bearchiveParamsTags can retrieve custom parameters of the document. We may want to exclude some parameters that we do not want to display.

    {% archiveParams params %}
        {% for field in params %}
            {% if field.Name != '文章作者' and field.Name != '发布日期' %} {# 结合 and 逻辑运算符 #}
                <div>
                    <span>{{field.Name}}:</span>
                    <span>{{field.Value}}</span>
                </div>
            {% endif %}
        {% endfor %}
    {% endarchiveParams %}
    

    This has been used!=And (not equal to)andThe logical AND operator is used to combine conditions, achieving finer-grained control.

Master the key points of conditional judgment

  • Boolean value judgmentIn{% if variable %}If such a condition, ifvariableIs a non-empty string, a non-zero number, a non-empty list/mapping, then it is consideredtrue; Otherwise, it is consideredfalse.
  • Common operators: The conditional expression of Anqi CMS template supports common comparison operators (==equal,!=Not equal to,>Greater than,<Less than,>=Greater than or equal to,<=Less than or equal to) and logical operators (andand,oror,notNot). In addition,inOperators can be used to check if a value exists in a list or string (such as{% if "关键词" in item.Title %})
  • Tag pairing and correct nesting: Allif-else-eliftags must have corresponding{% endif %}And correctly nested, avoid logical confusion or parsing errors.
  • Remove blank linesSometimes, in order to keep the template output tidy, we do not want toif-elseThe blank line generated by the tag itself appears in the final HTML. It can be removed by adding a hyphen after the%symbol{%-or-%}to remove whitespace before or after the tag, for example{%- if 条件 %}.

Summary

The AnQi CMS template includesif-elseConditional tags are an indispensable tool for building dynamic and flexible websites.It allows us to finely control the display logic of content based on various attributes of the content, the user's operational status, or the context of the page.Proficiently using these conditional judgments will greatly enhance the efficiency of template development and the performance of website content.


Frequently Asked Questions (FAQ)

  1. Q: Why is myifcondition judgment not working?A: Please first check if the variable names in the condition expression are spelled correctly (the Anqi CMS template is case-sensitive), and then confirm that the logic of the condition expression meets expectations (such as numerical comparison, string matching, etc.). If the variable is null, zero, or an empty string,{% if 变量 %}It will be judged as false. In addition, check{% if ... %}and{% endif %}whether it is correctly paired and nested.

  2. Q: How should I write to judge if a string variable contains a certain substring?A: The Anqi CMS template providescontaina filter to implement this feature. You can write it like this:{% if my_string_variable|contain:"目标子字符串" %}Ifmy_string_variableincluding"目标子字符串"The condition will be true.

  3. Q:{% if variable %}and{% if variable == true %}What is the difference?A:{% if variable %}Is a judgmentvariableof the boolean truth value. IfvariableIt is a non-empty string, non-zero number, non-empty list/mapping, or a boolean typetrue, which is considered to betrueHowever{% if variable == true %}Then it is a strict comparisonvariableWhether the value is equal to a boolean valuetrue. Usually, both can achieve the purpose for boolean variables; but for non-boolean variables, using it directly is more concise and general.{% if variable %}is more concise and general.

Related articles

How to use Django template engine syntax to efficiently display various dynamic content in AnQiCMS?

In AnQi CMS, you will find that the built-in Django template engine syntax is an extremely powerful and flexible tool, which can help you efficiently convert backend data into dynamic and lively content on the frontend page.Master this syntax, and you'll not only be able to display basic text and images, but also build complex, interactive dynamic pages, making your website vibrant.The template syntax design of Anqi CMS is very intuitive, it draws on the characteristics of the Django template engine and integrates the concise and efficient Go language.

2025-11-07

Where should the AnQiCMS template files be stored, and what file extensions are supported?

AnQiCMS is designed very clearly and flexibly in template file management, aiming to allow users to customize the appearance and functions of the website efficiently.If you are using AnQiCMS to build or maintain a website, understanding the location of template files and supported suffixes is the foundation for front-end development and customization.

2025-11-07

How to customize templates in AnQiCMS to change the overall visual style and layout of the website?

In this era that emphasizes brand and user experience, the visual style and layout of a website is the key to its successful operation.AnQiCMS (AnQiCMS) understands this point and therefore provides a highly flexible template customization feature, allowing users without a strong development background to create websites that meet their unique needs with a personalized touch.If you are considering changing the overall style of the website or want to design a dedicated layout for specific content, it will be very helpful to understand how to customize templates in AnQiCMS.

2025-11-07

How to manage custom fields in the content model of AnQiCMS and call them to display on the front-end page?

AnQi CMS is an efficient and customizable enterprise-level content management system, one of its core highlights is the 'flexible content model'.This feature greatly expands the management boundaries of website content, allowing us to create various and unique content structures according to actual business needs.Among these, custom fields (or custom parameters) play a crucial role, allowing our website content to go beyond traditional article titles, body, and summaries, and carry more personalized information, ultimately displaying flexibly on the front-end page.

2025-11-07

How to use the `for` loop tag to iterate and display list data in AnQiCMS template?

In AnQiCMS templates, dynamically displaying list data is one of the core operations for building rich website content.Whether it is displaying the latest articles, hot products, category lists, or any custom content collection, the `for` loop tag is your helpful assistant.It allows you to easily traverse data and customize the display of each item according to your needs.Understanding the basics of the `for` loop tag The `for` loop tag is a control structure in the AnQiCMS template engine used for iterating over collection data.

2025-11-07

How does AnQiCMS support the switching of multiple templates, as well as how to specify an independent template for a specific page or content type?

## The flexible aspects of AnQiCMS: How to handle multi-template switching and personalized page design A flexible template mechanism is crucial for a content management system to maintain competitiveness and adapt to diverse operational needs.AnQiCMS is an efficient enterprise-level content management system that has demonstrated excellent capabilities in this regard. It not only supports multi-template switching at the whole-site level but also provides detailed features for specifying independent templates for specific pages or content types. This is undoubtedly a powerful tool for websites that need to carry out refined content operations. Firstly

2025-11-07

How to retrieve and display the title, detailed content, summary, and recommended attributes of an article (document)?

In Anqi CMS, whether it is to display the detailed content of a single article or to preview multiple articles on the list page, flexibly obtaining and displaying the title, detailed content, introduction, and recommended attributes of the article is the foundation of website operation.The design of Anqi CMS makes this process intuitive and efficient, we mainly achieve it through template tags and variable calls.First, understand the template system of Anqi CMS is crucial.

2025-11-07

How to effectively retrieve and display a thumbnail, cover main image, or a collection of multiple images for an article?

In content operation, captivating images are an indispensable element to attract readers and enhance the quality of articles.AnQiCMS (AnQiCMS) understands this and provides a diverse and flexible set of features, whether it's for the thumbnails of article lists, the cover images on detailed pages, or rich multi-image collections, all can be easily obtained and displayed in the way you expect.How does AnQi CMS handle various images?In AnQi CMS, images are usually divided into several types to meet the display needs of different scenarios: * **Article Thumbnail (Thumb):**

2025-11-07