In AnQiCMS templates, skillfully useif-elseConditional judgment tag, making 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', add 'HOT' tag to an article in recommended status, or add a special style to the first item in the loop.if-elseConditional judgment tag, helping us easily implement these dynamic content display logic.
if-elseBasic syntax of tags
In the Anq CMS template,if-elseThe conditional judgment tag is defined using curly braces and the percent sign, and must appear in pairs.{% endif %}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,elifThe [else if abbreviation] tag comes into play:
{% if 条件1 %}
<!-- 当条件1为真时显示的内容 -->
{% elif 条件2 %}
<!-- 当条件1为假,且条件2为真时显示的内容 -->
{% else %}
<!-- 当所有条件都为假时显示的内容 -->
{% endif %}
The 'condition' can be a boolean value of a variable, a comparison expression between variables, or a complex expression containing logical operators.
Flexible and versatile application of condition judgment
if-elseThe power of tags lies in their ability to adapt to various complex business logic, making our content display more intelligent and dynamic.
Determine if the content exists or is empty.This is one of the most common application scenarios.For example, when we need to display a list of documents, if the list is empty, we prompt the user with 'No content available'.
archiveListorcategoryListTag 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, in
forthe loop, we can also useemptya subquery to achieve the same purpose, which is a more concise way to write:{% for item in archives %} <li><a href="{{item.Link}}">{{item.Title}}</a></li> {% empty %} <p>该列表没有任何内容。</p> {% endfor %}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.
Check if the image existsIf the document has a thumbnail (
item.ThumbIf so, the 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 %}
Special handling in the loop.In
forin the loop,forloopThe variable provides information about the current loop state, combined withifTags can be used to perform special handling on specific elements within a loop.Add special styles 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 styles for odd and even rows.:
{% for item in archives %} <li class="{% if forloop.Counter is odd %}odd-row{% else %}even-row{% endif %}"> {{item.Title}} </li> {% endfor %}
Distinguish content on different pages.When 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 achieved through template inheritance, sometimes it also controls through the judgment of the current page type within the same template file.
{% categoryDetail currentCategory %} {% if currentCategory.Id == 10 %} {# 假设当前页面是ID为10的分类页 #} <!-- 显示分类ID为10的专属内容 --> {% else %} <!-- 显示其他分类的通用内容 --> {% endif %}Handle complex logic and custom fields.The AnQi CMS allows us to customize fields for the content model. The data of these custom fields can also be accessed.
if-elsePerform conditional judgments. For example, customizedarchiveParamsTags can retrieve the 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 %}Here, we use
!=(not equal to) andandThe logical AND operator is used to combine conditions, achieving finer-grained control.
Mastering the key points of conditional judgment.
- Boolean value judgment.: In
{% if variable %}In such conditions, ifvariableIs a non-empty string, non-zero number, or non-empty list/mapping, it is consideredtrue; otherwise, it is consideredfalse. - Common operators: The conditional expression of AnQi CMS template supports common comparison operators
==equals,!=Not equal to,>Greater than,<Less than,>=greater than or equal to,<=Less than or equal to) as well as 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 %}). - Label pairing and correct nesting: All
if-else-elifLabels must all have corresponding{% endif %}, and correctly nested to avoid logical confusion or parsing errors. - Remove blank lines: Sometimes, for the neatness of template output, we do not want
if-elseThe blank lines generated by the tag itself appear in the final HTML. They can be removed from before or after the tag by adding a hyphen after the symbol.%to remove whitespace before or after the tag, for example{%-or-%}to remove whitespace before or after the tag, for example{%- if 条件 %}.
Summary
In the Anq CMS template,if-elseConditional judgment 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.Mastery of these conditional judgments will greatly enhance the efficiency and expressiveness of template development and website content.
Common Questions and Answers (FAQ)
Q: Why does my
ifcondition judgment not work?A: Please first check if the variable names in the condition expression are spelled correctly (Anqi CMS template is case-sensitive), and then confirm whether the logic of the condition expression meets expectations (such as numerical comparison, string matching, etc.). If the variable is an empty value, zero, or an empty string,{% if 变量 %}It would be deemed false. Moreover, check{% if ... %}and{% endif %}whether they are correctly paired and nested.Q: How should I write a string variable to check if it contains a certain substring?A: The Anqi CMS template provides
containa filter to achieve this feature. You can write it like this:{% if my_string_variable|contain:"目标子字符串" %}.my_string_variablecontains"目标子字符串"and the condition will be true.Q:
{% if variable %}and{% if variable == true %}What is the difference?A:{% if variable %}is to judgevariableThe boolean truth value. Ifvariableis a non-empty string, non-zero number, non-empty list/dictionary, or a boolean typetrue, it will be considered astrue.{% if variable == true %}is an exact comparisonvariableof the value with the boolean valuetrueGenerally, both are effective for boolean variables; however, using it directly is simpler and more universal for non-boolean variables.{% if variable %}is more concise and universal.