In the Auto CMS, when managing content, we often need to display different information according to different situations.For example, one blog post may have a thumbnail while another does not; or a module may only be displayed under specific conditions.ifLabels, can help us achieve these dynamicized content display needs.
The template engine of AnQi CMS supports syntax similar to Django, whereifLabels are the core tools for conditional judgment. They can determine 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 needed?ifTag 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 current page being accessed 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 judgment.ifLabels allow us to write more adaptable and user-friendly templates.
ifBasic usage of the tag
ifThe most basic structure of labels is{% if 条件 %}and{% endif %}. The code placed between these two labels is only executed when条件It will be displayed when true.
An example is to check if a variable exists or is true.In AnQiCMS, many variables are considered false when no value is assigned.
{% if archive.Thumb %}
<img src="{{ archive.Thumb }}" alt="{{ archive.Title }}">
{% endif %}
The meaning of this code is: ifarchive.ThumbThe path of the article thumbnail exists and has a value, then this image will be displayed. Otherwise, the code for the image part will be ignored.
IntroductionelseHandle alternative cases
When we want to display other content instead of just leaving it blank when the condition is not met, we can useelsetags. It acts asifThe supplement provides a mechanism to 'execute here if none of the preceding conditions are met'.
Continue with the thumbnail example, if the article does not have a thumbnail, we want to display a default placeholder image:
{% if archive.Thumb %}
<img src="{{ archive.Thumb }}" alt="{{ archive.Title }}">
{% else %}
<img src="/static/images/default-thumb.png" alt="默认占位图">
{% endif %}
So, whether the article has a thumbnail or not, there will be an image on the page to maintain the integrity of the layout.
More conditions:elifof the flexible use
In some cases, we may need to judge multiple mutually exclusive conditions. At this time,elif(abbreviated as else if) comes into play. It allows us to in aifCheck multiple conditions sequentially in the block, once a condition is met, the corresponding code will be executed, and the rest will be skipped.elifandelseThe block will be skipped.
For example, we want to use the "recommended attributes" of the articleFlag) to display different marks:
{% 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 executed according to the article'sFlagAttribute value, displaying the marks of 'Top News', 'Recommendation', or 'Normal'.
Combining complex conditions: logical operators
if标签不仅支持简单的值判断,还能与逻辑运算符结合,构建更复杂的条件表达式。AnQiCMS模板引擎支持常见的逻辑运算符,如and(Logical AND),or(Logical OR),not(Logical NOT), as well as comparison operators==(equals,)!=(not equal to,)<(less than,)>(greater than,)<=(Less than or equal to),>=(Greater than or equal to). In addition,inoperators can check if an element is contained in a set (such as a string, array).
Check multiple conditions to be true:
andWe only display "Hot Headlines" when the article is a "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 true:
orIf the article is "recommended" or has the "image" attribute, display a special style:{% if archive.Flag == 'c' or archive.Flag == 'p' %} <div class="special-highlight">...</div> {% endif %}Reverse judgment:
notIf there are no subcategories in the category, 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 relationship:
inIf certain specific keywords are included in the article'sKeywordsfield, display specific content.{% if "AnQiCMS" in archive.Keywords %} <span>安企CMS专属内容</span> {% endif %}
Combining the practice of AnQiCMS template tags
ifThe power of the label lies in its combination with various data labels provided by AnQiCMS (such asarchiveList/categoryDetailetc.),
Active state of the navigation menu:Commonly used in navigation lists, to add corresponding menu items for the current page.
activeClass 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, which is true when the current navigation item matches the current pagetrue.Handle list empty content:When using
forWhen traversing a 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 %}the cumbersome.
Precautions
- Strict grammar:All
{% if %}Labels must all have corresponding{% endif %}Close it,{% elif %}and{% else %}It is not necessary. - Type matching:When comparing, make sure that the types of the variables involved in the comparison are compatible; otherwise, you may get unexpected results.
- Blank line control:In the template,
ifThe label may introduce an additional blank line. If you need to strictly control the output, you canif/else/endifadd a hyphen in the-of the start and end delimiters of the label to remove the blank line generated by the label, for example{%- if condition -%}.
MasteredifThe usage of labels allows you to more flexibly and intelligently control the display of AnQiCMS website content, providing your visitors with a better browsing experience.
Common Questions (FAQ)
1. Can I useifNested statements within othersifstatement inside a statement block?Yes, AnQiCMS template engine fully supportsifnested statements. You can place a fullif/eliforelseblock inside any block as neededif…endifStructure, to handle more fine-grained logical judgments.
2. How to check if a string variable contains specific text?You can usecontainFilter 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 multipleifgood, or oneifCombineand/oroperator 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 aifCombineandororThe operator will be more concise and efficient. If these conditions are hierarchical or require executing completely different code blocks based on different conditions, then useif/elif/elseThe structure will be clearer. Avoid writing overly long and complex single conditional expressions to maintain code readability.