When managing content in AnQi CMS, we often need to display different information based on different situations.For example, one blog post may have a thumbnail while another does not;Or a module may only be displayed under certain conditions. In this case, flexibly use the conditional judgment in the template, that is,ifTags, can help us achieve these dynamic content display needs.
The template engine of Anqi CMS supports syntax similar to Django, whereifThe tag is the core tool for conditional judgment. It can decide which part of the content should be rendered and which part should be hidden based on the value of the variable or the result of the expression.
Why is it neededifTag for conditional judgment?
Imagine that we want a certain area of the website to intelligently adapt to different content states. For example:
- Display an image or a default placeholder:If the article has a cover image, it will display the cover; if not, it will display a preset default image.
- Active state of the navigation menu:The currently visited page is highlighted in the navigation menu.
- Distinguish content types:For the 'article' model, display author information; for the 'product' model, display price information.
- Handle empty data:When a list is empty, it should display 'No data' instead of a blank space.
All these scenarios cannot do without conditional judgments.ifTags allow us to create more adaptable and user-friendly templates.
ifBasic usage of tags
ifThe most basic structure of tags is{% if 条件 %}and{% endif %}. The code placed between these two tags, only when条件It will display when true.
A simple example is to check if a variable exists or is true.In AnQiCMS, many variables are considered false when they have no value.For example, we can determine whether an article has a thumbnail:
{% if archive.Thumb %}
<img src="{{ archive.Thumb }}" alt="{{ archive.Title }}">
{% endif %}
The meaning of this code is: ifarchive.Thumb(The thumbnail image path) exists and has a value, then this image will be displayed. Otherwise, the code for the image section will be ignored.
IntroductionelseHandle alternative cases
When we want to display other content when the condition is not met instead of just leaving it blank, we can useelsea tag. It acts asifThe supplement provides a mechanism to execute here if all previous conditions are not met.
Continue with the thumbnail example, if the article does not have a thumbnail, we want to display a default placeholder:
{% if archive.Thumb %}
<img src="{{ archive.Thumb }}" alt="{{ archive.Title }}">
{% else %}
<img src="/static/images/default-thumb.png" alt="默认占位图">
{% endif %}
This way, there will always be an image on the page to maintain the layout integrity, regardless of whether the article has a thumbnail.
More conditions:elifthe flexible application
In some cases, we may need to judge multiple mutually exclusive conditions. At this point,elifthe (else if abbreviation) tag comes into play. It allows us toifWithin the block, multiple conditions are checked in sequence. Once a condition is met, the corresponding code will be executed, and the restelifandelsewill be skipped.
For example, we want to base the article's "recommended properties" on the following conditions (Flag) to display different tags:
{% if archive.Flag == 'h' %}
<span class="badge hot">头条</span>
{% elif archive.Flag == 'c' %}
<span class="badge recommend">推荐</span>
{% else %}
<span class="badge normal">普通</span>
{% endif %}
This code will be based on the attributes of theFlagProperty value, shows the mark of "Headline", "Recommend" or "Normal".
Combine complex conditions: logical operators
ifLabels not only support simple value judgment, but can also be combined with logical operators to construct more complex conditional expressions. The AnQiCMS template engine supports common logical operators such asand(Logical AND),or(Logical OR),not(Logical NOT), as well as comparison operators==(equal to),!=(Not equal),<(Less than),>(greater than),<=(less than or equal to),>=(Greater than or equal to). Moreover,inOperators can check if an element is contained within a collection (such as a string, array).
Check if multiple conditions are met:
andWe will only display 'Hot Headline' when the article is 'Top Story' and the views exceed 1000:{% if archive.Flag == 'h' and archive.Views > 1000 %} <span class="badge super-hot">热门头条</span> {% endif %}Check if any condition is met:
orIf the article is 'recommended' or has the 'image' attribute, a special style should be displayed:{% if archive.Flag == 'c' or archive.Flag == 'p' %} <div class="special-highlight">...</div> {% endif %}Reverse judgment:
notIf the category does not have subcategories, display the document list under the category:{% if not category.HasChildren %} {% archiveList archives with type="list" categoryId=category.Id limit="8" %} {# ... 显示文档列表 ... #} {% endarchiveList %} {% endif %}Check for inclusion:
inIf certain specific keywords are included in theKeywordsfield, display specific content.{% if "AnQiCMS" in archive.Keywords %} <span>安企CMS专属内容</span> {% endif %}
Practice with AnQiCMS template tags
ifThe power of tags lies in their combination with various data tags provided by AnQiCMS (such asarchiveList/categoryDetailetc.)
Active state of the navigation menu:Commonly used in navigation lists, to add menu items corresponding to the current page
activethe class name.{% navList navs %} {% for item in navs %} <li class="{% if item.IsCurrent %}active{% endif %}"> <a href="{{ item.Link }}">{{ item.Title }}</a> </li> {% endfor %} {% endnavList %}Here
item.IsCurrentIs a boolean value, when the current navigation item matches the current pagetrue.Handle list empty content:While using
forWhen traversing the list, if the list is empty, you can useemptyLabels to display prompt information, which is actuallyifA shorthand form of judgment, very practical.{% archiveList archives with type="page" limit="10" %} {% for item in archives %} {# ... 显示文章内容 ... #} {% empty %} <p>暂无相关文章。</p> {% endfor %} {% endarchiveList %}This code avoids manual writing
{% if archives %}...{% else %}of繁琐ness.
Points to note
- Syntax is strict:All
{% if %}tags must have corresponding{% endif %}Come to a close,{% elif %}and{% else %}It is not necessary. - Type matching:When comparing, make sure the variable types involved are compatible; otherwise, you may get unexpected results.
- Line spacing control:In the template,
ifLabels may introduce extra blank lines. If you need to control the output strictly, you canif/else/endifadd dashes in the start and end delimiters of-to remove the blank lines generated by the tags, for example{%- if condition -%}.
MasteredifThe use of tags, you can control the display of AnQiCMS website content more flexibly and intelligently, providing your visitors with a better browsing experience.
Frequently Asked Questions (FAQ)
1. Can IifNested statementsifIs this statement?Yes, AnQiCMS template engine fully supportsifnested statements. You can place a fullif/eliforelsestatement inside any block as neededif...endifStructure, to handle more refined logical judgments.
2. How to check if a string variable contains specific text?You can usecontainA filter to determine if a string variable contains a specific text. For example, to checkarchive.Titlewhether it contains “AnQiCMS”, you can write as follows:{% if archive.Title|contain:"AnQiCMS" %}This will returntrueorfalseThus, control the display of content.
3. If I need to judge multiple conditions, is it using multipleifOr is it goodifCombineand/orIs the operator good?In most cases, if multiple conditions are in parallel relationships (i.e., they all act on the same judgment object, such asarchive.Flag == 'h' and archive.Views > 1000), then use oneifCombineandororOperators will be more concise and efficient. If these conditions are hierarchical or require different code blocks to be executed based on different conditions, then useif/elif/elseThe structure will be clearer. Avoid writing overly long and complex single conditional expressions to maintain readability.