In the template design of AnQi CMS, in order to achieve dynamic content display and complex layout control, conditional logic judgment is an indispensable part. As a website operator, I am well aware of the flexible application ofif/elif/elseLogical judgment labels, which can enable us to display various page content based on different data states or business requirements, thereby enhancing user experience and the interactivity of the website.
The template engine of AnQi CMS supports syntax similar to Django template engine, which allows users familiar with other mainstream CMS template syntaxes to quickly get started. Conditional judgment tags are used{% ... %}of the form defined, and must appear in pairs, that is, eachifLabels must all have correspondingendiftag to end a conditional judgment block.
the basic conditional judgment in the AnQi CMS template
In the template of AnQi CMS, the most basic conditional judgment statement isiftags. It is used to determine if 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 is very practical.
A simpleifJudgment can be constructed in this way:
{% if variable_name %}
<!-- 当 variable_name 为真时显示的内容 -->
{% endif %}
Herevariable_nameCan be any data passed directly from the backend to the template, such asarchive.Id/item.TitleIn the template context of Anqi CMS, numeric variables are true if non-zero, strings are true if non-empty, and lists or arrays are true if non-empty.nilEmpty values, empty strings, or zero values are usually considered false. We can even directly test boolean variables.
IntroductionelsePerform a two-option judgment
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 solution when the condition is false. At this time,elseLabels come in handy.ifWithelseCombined, it forms a binary logical branch, ensuring that some content is always rendered regardless of the condition.
Its structure is as follows:
{% if condition_expression %}
<!-- 条件为真时显示的内容 -->
{% else %}
<!-- 条件为假时显示的内容 -->
{% endif %}
For example, we can determine if a document has a thumbnail, and if not, display a default placeholder image:
{% 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 it is necessary to check them one by one,elif(Abbreviation of else if) tag provides an elegant solution.elifAllow us to initializeifIf the condition is not met, continue checking other conditions until a true condition is found. If all conditions are false,ifandelifthe optional block (if it exists) will be executed.elsewill be executed.
The typical structure of a multiple condition judgment is as follows:
{% if first_condition %}
<!-- 当第一个条件为真时执行 -->
{% elif second_condition %}
<!-- 当第一个条件为假且第二个条件为真时执行 -->
{% elif third_condition %}
<!-- 当前两个条件为假且第三个条件为真时执行 -->
{% else %}
<!-- 所有条件都为假时执行 -->
{% endif %}
A practical example may be in a loop based on the recommended attributes of the document (Flag) to display different styles or markers.flagAttributes support multiple values, such ash(Headlines),c(Recommended) 等。
{% 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 operations in conditional judgments
The template engine of AnQi CMS supports the use of various logical and comparison operators in conditional expressions, which greatly enhances the flexibility of conditional judgment. Common operators include:
- Comparison operators:
==(等于), English!=(Not equal to),<(Less than),>(Greater than),<=(Less than or equal to),>=(greater than or equal to). - Logical operators:
and(logical and),or(logical or),not(logical not). - Member operator:
in(check if an element is in a set).
These operators can be combined to build complex judgment logic. For example, we can determine whether a numeric 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 loops
Conditional judgment labels andforThe combination of loop tags is a commonly used pattern in security CMS templates to achieve dynamic content display. For example, when iterating over a list, we can use according toforloop.Counter(The current loop index, starting from 1) to perform special processing on 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 elements in a list.
Optimize the conditional logic in template code.
To maintain the neatness and readability of the template code, Anqi CMS also provides a method to remove blank lines occupied by logic tags.if/elif/else/endifat the front or back of the tags inside.-Symbols, which 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, in the AnQi CMS template,if/elif/elseThe logic judgment tag provides strong 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 it is based on user identity, data status, or other business logic, they can build pages that respond quickly and provide excellent user experience.This not only enhances the functionality of the website, but also lays a solid foundation for refined operation and the implementation of content marketing strategies.
Common Questions and Answers (FAQ)
1. If I forget toifadd at the end of theendifWhat will happen to the label?
In the AnQi CMS template engine, all conditional judgment tags (such asif,elif,else) must end withendifLabel is explicitly closed. If missingendifThe template engine will report an error during parsing, causing the page to fail to render normally, and it will usually throw an error message such as 'unclosed tag'.Therefore, be sure to ensure that each conditional block has the correct ending tag.
2. Can I access the global configuration information of the site?ifNested other statements insideifstatement inside a statement block?
Yes, the template engine of Anqi CMS fully supportsifnested statements. This means you can have oneif/eliforelseThe internal structure of the block, redefine the conditional judgment logic. This nested mechanism allows you to build very complex and fine-grained page logic to meet 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 the template of AnQi CMS, you can directly useif variable_nameto check if a variable is empty or undefined. Ifvariable_nameThe value ofnil、空字符串、数字0、布尔falseIt will be evaluated as an empty array/list orfalseThus triggeringelseblock (if it exists). You can also explicitly useif variable_name == nilCheck this, but it is usually redundant because the template engine's truthy evaluation is sufficient. For a stricter check of empty strings, you can useif variable_name == "".