In the Anqi CMS template world, we often need to display content based on different conditions, or repeat a series of data, at this time, ifandforThese logical tags are particularly important. They are the foundation for building dynamic content and achieving flexible layouts in templates, and they can help us accurately control the presentation of every piece of information on the web page.
Condition logic in AnQiCMS templates:ifTag
ifThe role of tags in a template is like a smart switch, allowing us to decide whether to display a part of the content based on specific conditions.This is very practical in many scenarios, such as displaying different user greetings, deciding whether to load images based on whether the article has a thumbnail, or displaying "In stock" or "Out of stock" based on the product status.
Its basic usage is very intuitive: with{% if 条件 %}and ends with{% endif %}End.If the condition is true (True), the content inside the tag will be rendered and displayed; if the condition is false (False), this part of the content will be ignored.
Of course, real-world needs are often not as simple as 'yes' or 'no'.ifTags also supportelif(else if abbreviation) andelseClauses, let us be able to handle multiple conditional branches.
For example, we may need to display different navigation links based on the user's permission level:
{% if user.IsAdmin %}
<a href="/admin/dashboard">管理后台</a>
{% elif user.IsVip %}
<a href="/user/vip-content">VIP专属内容</a>
{% else %}
<a href="/user/login">登录/注册</a>
{% endif %}
When evaluating conditions, we can use multiple expressions:
- Check if a variable exists or is not empty:
{% if variable %}Will judgevariableIs itnilor empty string, zero value orfalse. - Comparison operation:
{% if item.Views > 100 %}(greater than),{% if archive.Id == 1 %}(equal to),{% if price <= 50 %}(less than or equal to) etc. - Logical operations:Use
and/or/notTo combine or negate conditions, for example{% if category.HasChildren and category.IsActive %}. - Member check:
{% if "关键词" in archive.Tags %}Can check if a value is included in a string or collection.
By these flexible conditional judgments, we can allow the template to present a variety of content combinations based on the real-time status of the data, greatly enhancing the interactivity and personalization of the website.
Flexible data traversal:forLoop tags
forTags are a powerful tool for processing datasets, allowing us to iterate over lists, arrays, or other iterable objects and generate duplicate content structures for each element.This is essential when displaying article lists, product categories, navigation menus, or comment lists.
forThe basic structure of the loop is:{% for item in collection %}, and ends with:{% endfor %}. Inside the loop body,itemthe variable represents the current element of the collection being processed.
For example, to display a list of articles:
{% archiveList archives with type="list" limit="5" %}
{% for article in archives %}
<div class="article-item">
<h2><a href="{{ article.Link }}">{{ article.Title }}</a></h2>
<p>{{ article.Description }}</p>
<span>发布日期:{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
</div>
{% endfor %}
{% endarchiveList %}
InforIn the loop, there are some built-in special variables and functions that can help us better control the loop:
forloop.Counterandforloop.Revcounter:forloop.CounterReturn the current loop index starting from 1 (such as 1, 2, 3...), whileforloop.RevcounterReturns the index from the total count in reverse order (e.g., if the total is 5, it returns 5, 4, 3, ...).This is very useful for adding odd-even styles or special markers (such as "Hot Recommendations" only displayed for the first few items) to list items.emptyThe clause:WhenforWhen the collection being traversed is empty,{% empty %}the content within the block will be executed. This is better than usingifJudge whether the set is empty before writing the loop for better conciseness:{% archiveList articles with type="list" categoryId="999" %} {# 假设这个分类没有文章 #} {% for article in articles %} <div class="article-item">...</div> {% empty %} <p>抱歉,该分类下暂时没有文章。</p> {% endfor %} {% endarchiveList %}modifier:
forTags can be配合reversedandsortedModifiers to control the order of traversal.reversedLet the set be traversed in reverse order,sortedThen try to sort the set before traversing it.{% for item in categories reversed %} {# 倒序显示分类 #} {% endfor %} {% for number in numberList sorted %} {# 对数字列表排序后显示 #} {% endfor %}cycleTags:cycleThe tag can output a few predefined values in order during each loop, commonly used to apply different CSS classes to alternating list items to achieve a zebra line effect.{% for product in products %} <div class="product-item {% cycle 'odd' 'even' %}"> ... </div> {% endfor %}
Combine with actual scenarios to enhance the template's expression power
ifandforThe true power of tags lies in their combination with other AnQiCMS tags. For example, we can first usearchiveListRetrieve article data and thenforLoop through these articles and use them inside the loopifLabel to determine the specific properties of each article, such as whether it has a thumbnail ({% if item.Thumb %}), whether it is a pinned article ({% if "h" in item.Flag %}Thus, it decides how to display content.
In the pagination scenario,archiveListcooperatetype="page"return pagination data, thenforloop is used to traverse the data items on the current page, andpaginationThe tag is responsible for rendering pagination navigation, which may also be usedifto determine the current page and total number of pages.
In addition, when we use the templateiforforWhen labeling, you may notice that the generated HTML contains many blank lines. AnQiCMS provides a clever solution: add dashes to the start or end symbols of logical tags.-For example{%- if 条件 %}or{% endfor -%}This can remove the tag itself and any whitespace on both sides (including newline characters), making the generated HTML more compact and clean.
Through proficiencyifandforTags and their various advanced usages allow us to build highly dynamic, responsive, and content-rich web pages in AnQiCMS, meeting various complex content operation needs.
Frequently Asked Questions (FAQ)
How to
iforforDo you use filters (Filter) in tags to process data?You canifOr part of the statement conditionforUse filters when outputting variables inside a loop. For example,{% if article.Title|length > 10 %}Determine if the length of the article title is greater than 10 or{{ article.Description|truncatechars:50 }}InforTruncate the article description in the loop. The syntax of the Filter is usually{{ 变量|过滤器名:参数 }}.Why did my template stop working when it was used
iforforAfter the tag, the HTML output will have many blank lines?This is because the logical tag itself (such as{% if %}/{% endfor %}A newline character will occupy a line in the template file and will produce a newline when rendered. To generate a more compact HTML output, you can add a hyphen inside the start or end tags of the logical label.-For example, will{% if condition %}changed to{%- if condition %}Or will{% endfor %}changed to{% endfor -%}This will remove the tag itself and the whitespace on both sides, including newlines.How can I determine if a variable is null or does not exist?In `