The conditional logic in AnQi CMS template: flexible application{% if ... elif ... else ... %}Achieving multi-branch control
As an experienced website operations expert, I am well aware that flexible and variable website content display is crucial for user experience and operational efficiency.AnQiCMS (AnQiCMS) with its efficient and customizable features, provides us with powerful content management capabilities.How to display different content according to different situations in template creation to achieve refined content operation?This cannot help but mention the crucial conditional judgment statements in its Django-like template engine:{% if ... elif ... else ... %}.
This tag set allows us to execute different code blocks in the template based on specific conditions, making the website content dynamic and responsive.It is not only the basis for personalized display, but also the key to improving user interaction and information communication efficiency.
The basics of conditional judgment:{% if ... else ... %}Yes and no
In AnQi CMS templates, the most basic conditional judgment is{% if 条件 %} ... {% endif %}. It's like a simple switch, when the "condition" is true, executeifandendifContent between; if the condition is not met, this content will be ignored.
For example, we may want to display a welcome message after the user logs in, or a login prompt if not logged in.
{% if is_logged_in %}
<p>欢迎回来,尊敬的用户!</p>
{% endif %}
If we need to provide an alternative when the condition is not met,{% else %}Labels come in handy:
{% if is_logged_in %}
<p>欢迎回来,尊敬的用户!</p>
{% else %}
<p>您好,请先<a href="/login">登录</a>或<a href="/register">注册</a>。</p>
{% endif %}
Hereis_logged_inCan be a boolean variable passed from the backend to the template. The condition can be any expression that can be evaluated as true (true) or false (false).
Handle multiple conditional branches:{% elif ... %}The exquisite essence of
When our content display logic is no longer just a simple "yes" or "no", but needs to selectively display content based on multiple mutually exclusive conditions,{% elif ... %}(abbreviated as 'else if') has become an indispensable tool. It allows us to in aifIn a statement, a series of conditional branches are defined, each of which is checked in turn if the previous condition is not met.
Imagine, we are building a news detail page, which needs to display different tags or styles according to the article's "recommended attributes" (Flag)})
{% archiveDetail current_archive %} {# 假设获取当前文章详情 #}
<h1 class="article-title">{{ current_archive.Title }}</h1>
{% if current_archive.Flag | contain:"h" %} {# 检查是否包含“头条”属性 #}
<span class="badge badge-primary">头条</span>
{% elif current_archive.Flag | contain:"f" %} {# 检查是否包含“幻灯”属性 #}
<span class="badge badge-info">幻灯</span>
{% elif current_archive.Flag | contain:"c" %} {# 检查是否包含“推荐”属性 #}
<span class="badge badge-success">推荐</span>
{% else %}
<span class="badge badge-secondary">普通文章</span>
{% endif %}
<div class="article-content">{{ current_archive.Content | safe }}</div>
{% endarchiveDetail %}
In this example, the system will first check if the article is a "top news", if so, it will display the "top news" tag and skip the subsequent judgment.If it is not, then continue to check whether it is a 'slide', and so on.If allifandelifOnly when none of the conditions are met will the execution take placeelseContent within a block. This sequential execution feature allowselifIt is very efficient and intuitive when dealing with priority or mutual exclusion conditions.
Delve deeper into the mysteries of conditional judgment.
Masterif/elif/elseThe basic usage is just the first step, to master the Anqing CMS template, we still need to understand some advanced details:
The diversity of conditional expressions:In addition to direct variable judgment, we can also use various comparison operators in conditions (
==equal,!=Not equal to,<Less than,>Greater than,<=less than or equal to,>=greater than or equal to) and logical operators (andand,oror,notnot). For example,{% if archive.Views > 100 and archive.CommentCount > 10 %}you can check the number of page views and comments at the same time.inOperators are also very useful, such as{% if item.Id in selected_ids %}Used to determine whether a certain ID is in the given list.Judgment of 'true value' and 'false value':In Anqi CMS template, some values are implicitly evaluated as
trueorfalse:- non-zero numbers (for example
1,-5) are usuallytrue, zero (0) isfalse. - non-empty string (
"hello") and list (["a", "b"]) usually istrue, empty string ("") and empty list ([]) isfalse. - Boolean
truethat istrue,falsethat isfalse. nilornothing(Empty value) is usuallyfalse. This means you can simplify some judgments, such as{% if category.HasChildren %}It willHasChildrenattribute astrueto take effect, without having to write{% if category.HasChildren == true %}.
- non-zero numbers (for example
nested conditions:In order to handle more complex logic,
if/elif/elseSentences can be nested layer by layer. But remember, the purpose of the template is to display data, and complex logic should be handled as much as possible on the backend (controller), keeping the template clear and maintainable.Whitespace control:In the template, the conditional judgment tag itself may introduce unnecessary blank lines in the output HTML. To maintain the cleanliness of the output, you can use
{%-and-%}Syntax is used to control the generation of whitespace. For example,{%- if condition %}It will remove the whitespace on the left side of the tag, but{%- endif -%}It will remove the whitespace on both sides of the tag. This is very useful for generating compact HTML structures.{# 可能会产生空行 #} {% if article.is_hot %} <p>热门文章</p> {% endif %} {# 使用空白符控制,避免空行 #} {%- if article.is_hot -%} <p>热门文章</p> {%- endif -%}
Summary
The AnQi CMS template includes{% if ... elif ... else ... %}The combination tag provides powerful content dynamicization capabilities for website operators.Whether it is a simple yes-or-no choice or a complex multi-branch judgment, they can all help us intelligently display the most appropriate and attractive content according to different conditions.By flexibly applying these conditional logic, coordinating with good operators and whitespace control, we can build high-quality websites with better user experience and lower maintenance costs.
Frequently Asked Questions (FAQ)
1. Why my{% if ... %}The judgment result does not match the expected?This is usually due to improper use of variable types, values, or operators in the conditional expression. Please check:
- Does the variable exist or is it empty?
nilvalue, empty string, empty list, number0usually be evaluated asfalse. - whether the data type matches?For example,
"10"(string) with10(number) may not be equal under strict comparison. - Are the operators correct?Make sure to use the correct comparison operator (
==,>) and logical operator (and,or,not)
2. Use{% if ... %}How to avoid extra blank lines in the output HTML?You can use whitespace to control syntax. Add a hyphen on the left or right side of the tag.-For example,{%- if condition -%}Remove the blank lines on both sides of the tag and its content. This is particularly useful when generating compact HTML structures or handling inline elements.
**3.{% elif ... %}and `{%