In the development and maintenance of website templates, we often encounter the need to display or hide different content based on specific conditions.This dynamic content display logic is crucial for improving user experience, realizing personalized functions, and optimizing website structure.AnQiCMS (AnQiCMS) as a powerful content management system provides a flexible template engine, where conditional judgments (if/else) Tag is the core tool to achieve this goal.
The template engine syntax of Anqi CMS is similar to Django, which allows developers to use concise and intuitive tags to control the generation of page content.By cleverly using conditional judgments, we can make the website content smarter and more closely aligned with the actual access situation of users.
Master the basic conditional judgment syntax
In the Anqi CMS template, conditional judgment tags are used in the form of{% if ... %}and ends with{% endif %}End. This is the most basic usage. The content inside the parentheses will be displayed when the condition inside the brackets is true; otherwise, it will not.
For example, we may need to check if a variable exists or is empty. Suppose we are displaying the details of an article, and we only want to display it when the article title exists:
{% if archive.Title %}
<h1>{{ archive.Title }}</h1>
{% endif %}
here,archive.TitleRepresents the article title. If the article title has a value, this<h1>the tag and title content will appear on the page; if the title is empty, then the entire<h1>The tag and its content will not be rendered.
Introducing the 'else' branch:if-else
At times, when a condition is not met, we need to provide an alternative to display different content. At this point,elsethe tag comes into play. It is withifTags used together to form a mutually exclusive logical branch:
{% if archive.Thumb %}
<img src="{{ archive.Thumb }}" alt="{{ archive.Title }}">
{% else %}
<img src="/static/images/default-thumb.jpg" alt="默认缩略图">
{% endif %}
In this example, if the article has a thumbnail (archive.ThumbIf there is a thumbnail of the article, it will be displayed; if not, a default thumbnail will be displayed.This ensures the integrity of the page layout, avoiding blank or style issues due to missing images.
Handling multiple conditions:if-elif-else
When we need to handle more than two conditions, instead of multiple mutually exclusive cases,elif(else if abbreviation) tag is particularly important.It allows us to check a series of conditions in order until we find the first one that meets the condition and execute the corresponding code block.If allifandelifif none of the conditions are met, the lastelseblock (if it exists) will be executed as the default case.
For example, in an article list, we might want to display different tags based on the article's “recommended attribute”Flag) to display different tags:
{% if item.Flag == 'h' %}
<span class="flag-hot">热点</span>
{% elif item.Flag == 'c' %}
<span class="flag-recommend">推荐</span>
{% elif item.Flag == 'f' %}
<span class="flag-slide">幻灯</span>
{% else %}
<!-- 其他文章不显示特殊标记 -->
{% endif %}
here,item.FlagIndicates the recommended attribute of the article (such as fromarchiveListTagging articles from the list. The system will check in sequence whether the article is a hot spot, recommended, or slideshow, and display the corresponding tags. If none of them, no special tags will be displayed.
The practice scenario of flexibly using conditional judgment
The power of conditional judgment lies in its ability to deeply integrate with the various tags and data models provided by Anqi CMS, enabling extremely flexible content control.
Hint when the list content is empty:When using
archiveListorcategoryListWhen using the tag to obtain a data list, if the list is empty, we can useifthe statement to determine the length of the list variable to display the prompt 'No content' instead of leaving it blank. For example,{% if archives|length > 0 %}Then iterate through the list,{% else %} <div>暂无相关文章</div> {% endif %}.Current selected state of the navigation menu:While building the navigation menu,
navListthe tags returned byitem.IsCurrentAn attribute is very useful. We can use it to determine whether the current navigation item is the page the user is visiting and add aactiveclass to highlight:<li {% if item.IsCurrent %}class="active"{% endif %}> <a href="{{ item.Link }}">{{ item.Title }}</a> </li>Display features controlled by the system settings:Of Security CMS
systemTags can retrieve the global configuration information of the website. For example, we can determine if the website is closed and display the corresponding prompt page:{% system siteStatus with name="SiteStatus" %} {% if siteStatus == 0 %} {# 假设0代表关闭状态 #} {% system closeTips with name="SiteCloseTips" %} <div class="site-closed-message"> {{ closeTips|safe }} </div> {% else %} <!-- 正常网站内容 --> {% endif %}Please note, the document
help-setting-system.mdin网站状态is for clarification当你选择为闭站状态下,用户将只会看到闭站提示信息。This indicates that the shutdown logic has already been handled at the system level, and the template level may be more used for judgment of other custom system parameters.Custom field personalized display:By
archiveDetailorcategoryDetailThe custom field obtained can determine how to display it based on its existence or specific value. For example, if the product model has a custom field calledPrice:{% archiveDetail productPrice with name="Price" %} {% if productPrice and productPrice > 0 %} <p>价格: {{ productPrice }} 元</p> {% else %} <p>价格: 询价</p> {% endif %}Handle the availability of pagination links:In
paginationThe pagination object returned by the tag,pages.PrevPageandpages.NextPageCan be used to determine whether the previous page or next page exists, thus deciding whether to display the corresponding navigation button.{% if pages.PrevPage %} <a href="{{ pages.PrevPage.Link }}">上一页</a> {% else %} <span class="disabled">上一页</span> {% endif %}
Pay attention to the notes when writing conditional judgments
When writing conditional judgments, there are some tips that can help us write clearer and more efficient code:
- Be clear about the end tag:Every one
{% if %}must have corresponding{% endif %}. If usedeliforelse, they must beifandendifbetween. - Use logical operators:You can use
and/or/notetc. logical operators to combine more complex conditions, such as{% if user.IsLoggedIn and user.IsAdmin %}. - Variable existence judgment:Simply place the variable name in
ifthe statement, you can judge whether the variable exists and is not empty (for strings, numbers, lists, etc.). For example,{% if archive.Content %}it will be inarchive.ContentTrue when not empty. - Precise comparison:You can use
==(equal to),!=(Not equal),<(Less than),>(greater than),<=(less than or equal to),>=Comparison operators such as (greater than or equal to). - Remove extra spaces:Use within conditional tags.
{%-or-%}You can remove whitespace before or after the tag line, which is very useful for generating neat HTML code, especially when loop or conditional statements may introduce additional newline characters. For example:{%- if condition -%}.
By flexibly using the conditional judgment tags in the Anqi CMS template, we can create a responsive, feature-rich, and more intelligent website for content display.This has improved the professionalism of the website and also brought visitors a better browsing experience.
Frequently Asked Questions (FAQ)
1. What types of operators can I use in conditional statements?
You can use a variety of operators in conditional statements in AnQi CMS. In addition to the equality operators mentioned earlier,==Not equal!=) greater than (>) less than (<In addition to comparison operators, you can also use logical operators, such asand(Logical AND),or(Logical OR) andnot(Logical NOT) to combine or negate conditions. For example,{% if item.Views > 100 and item.Flag == 'h' %}In addition, you can even perform simple arithmetic operations in conditional judgments, such as{% if item.Price * item.Quantity > 500 %}.
2. How to apply different styles to different items in a loop?
InforIn a loop, you can use conditional judgments combined with the properties of the loop variable to dynamically apply styles. For example,forloop.CounterYou can get the current loop index (starting from 1),forloop.RevcounterYou can get the remaining number of loop iterations. You can add the first item in the loop like thisactiveClass:
{% for item in archives %}
<div class="list-item {% if forloop.Counter == 1 %}active{% endif %}">
{{ item.Title }}
</div>
{% endfor %}
You can also combine the properties of the data itself, such asitem.IsCurrentoritem.StatusTo judge, apply different CSS classes based on different values.
What will happen if the variable referenced in the conditional judgment does not exist or is empty?
In the Anqi CMS template, when you areifIn a statement where a variable is directly referenced that does not exist or exists but has an empty value (such as an empty string, a number 0, nil, an empty list, or an empty object), the condition will be evaluated as false (falseThis is a convenient feature, as it allows you to safely check for the existence of data without causing template rendering errors. For example,{% if archive.Author %}only