In Anqi CMS template design, in order to achieve dynamic content display and complex layout control, conditional logic judgment is an indispensable part. As a website operator, I know the importance of flexible applicationif/elif/elseLogical judgment tags that allow us to present a variety of page content based on different data states or business needs, thereby enhancing user experience and website interaction.
The AnQi CMS template engine supports syntax similar to the Django template engine, which allows users familiar with other mainstream CMS template languages to quickly get started. Conditional tags are used.{% ... %}forms definition, and they must appear in pairs, that is, eachiftags must have correspondingendiftags to end a conditional block.
The basis of conditional judgment in Anqi CMS templates
In Anqi CMS template, the most basic conditional judgment statement isiftag. It is used to determine whether 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 becomes very useful.
A simpleifJudgment can be constructed like this:
{% if variable_name %}
<!-- 当 variable_name 为真时显示的内容 -->
{% endif %}
Herevariable_nameIt can be any data directly passed from the backend to the template, for examplearchive.Id/item.TitleAnd in the context of AnQi CMS templates, numeric variables are true if not zero, strings are true if not empty, lists or arrays are true if not empty, andnilValues such as empty, empty strings, or zero are usually considered false. We can even directly evaluate boolean variables.
IntroductionelsePerform a yes/no decision
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 when the condition is false. At this point,elsethe label comes into play.ifwithelseCombine to form a binary branch option, ensuring that no matter the condition, part of the content will always be rendered.
The structure is as follows:
{% if condition_expression %}
<!-- 条件为真时显示的内容 -->
{% else %}
<!-- 条件为假时显示的内容 -->
{% endif %}
For example, we can determine whether a document has a thumbnail, and if not, display a default placeholder:
{% 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 needing to check them one by one,elifthe (else if abbreviation) tag provides an elegant solution.elifallows us to initializeifAfter a condition is not met, continue checking other conditions until a true condition is found. If allifandelifconditions are false, then the optionalelseblock (if it exists) will be executed.
The typical structure of a multi-condition judgment is as follows:
{% if first_condition %}
<!-- 当第一个条件为真时执行 -->
{% elif second_condition %}
<!-- 当第一个条件为假且第二个条件为真时执行 -->
{% elif third_condition %}
<!-- 当前两个条件为假且第三个条件为真时执行 -->
{% else %}
<!-- 所有条件都为假时执行 -->
{% endif %}
A practical example may be to display different styles or markers in a loop based on the recommended properties of the document(Flag) to display different styles or markers.flagThe property supports multiple values, such ash(Headline),cRecommended, etc.
{% 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 operation in conditional judgment
The AnQi CMS template engine supports the use of various logical and comparison operators in conditional expressions, which greatly enhances the flexibility of conditional judgments. Common operators include:
- Comparison operator:
==(equals,)!=(not equal,)<(less than,)>(greater than,)<=(less than or equal to),>=(greater than or equal to). - Logical operator:
and(logical AND),or(logical OR),not(logical NOT). - member operator:
in(Check if the element is in the set).
These operators can be combined to form complex judgment logic. For example, we can determine whether a numerical 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 loop usage
Conditional judgment tag andforThe combination of loop tags is a common pattern used in Anqi CMS templates to achieve dynamic content display. For example, when iterating over a list, we can according toforloop.Counter(The current loop index, starting from 1) to handle 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 position elements in a list.
Optimize the conditional logic in the template code.
In order to maintain the neatness and readability of the template code, Anqi CMS also provides a method to remove the empty lines occupied by logical tags. Inif/elif/else/endifusing before or after the tags.-The symbol 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, within the AnQi CMS template,if/elif/elseLogic judgment tags provide powerful 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 based on user identity, data status, or other business logic, and can build responsive and excellent user experience pages.This has enhanced the functionality of the website and also laid a solid foundation for refined operation and content marketing strategies.
Frequently Asked Questions (FAQ)
1. If I forget toifadd at the end of the statement,endifWhat will happen to the tags?
In the AnQi CMS template engine, all conditional judgment tags (such asif,elif,else) must end withendifExplicitly close the tag. If you miss itendif, the template engine will report an error during parsing, causing the page to fail to render normally, and it will usually throw an error such as 'unclosed tag'.Therefore, be sure to ensure that each conditional block has the correct closing tag.
2. Can IifNested other statements insideifIs this statement?
Yes, the template engine of Anqi CMS fully supportsifNested statements. This means you can put one in anotherif/eliforelseInside the block, define a new conditional judgment logic. This nested mechanism allows you to build very complex and fine-grained page logic to meet the needs of 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 AnQi CMS templates, you can directly useif variable_nameto check if a variable is empty or undefined. Ifvariable_namehas a value ofnil, an empty string, a number0and Booleanfalseor an empty array/list, it will be evaluated asfalsethus triggeringelseblock (if it exists). You can also explicitly useif variable_name == nilCheck it, but this is usually unnecessary because the template engine's truthy evaluation is sufficient. For a stricter check of empty strings, you can useif variable_name == "".