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

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.