How to flexibly control the conditional display and loop iteration of logic tags such as `if` and `for` in the template?

Calendar 👁️ 69

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:Useand/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)

  1. How toiforforDo 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{{ 变量|过滤器名:参数 }}.

  2. Why did my template stop working when it was usediforforAfter 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.

  3. How can I determine if a variable is null or does not exist?In `

Related articles

How to use the `pagination` tag to generate a beautiful pagination navigation for articles or product lists?

In website operation, as the content volume continues to grow, whether it is articles, products, or other lists, how to efficiently organize and display these contents while ensuring a smooth user browsing experience and a friendly search engine is a problem that needs to be carefully considered.Page navigation is the key tool to solve this problem.AnQiCMS provides a powerful and flexible `pagination` tag that allows you to easily create beautiful and functional pagination navigation for various lists.

2025-11-08

How to use the `linkList` tag to display the list of friends' links on the website?

During the operation of our website, friendship links not only help to increase the amount of traffic, but are also an indispensable part of SEO optimization.A healthy link ecosystem that can effectively pass on weight and enhance the authority of the website.In AnqiCMS, managing and displaying friend links is very convenient, mainly due to its built-in `linkList` tag.This article will introduce in detail how to use the `linkList` tag to display the friend link list on your AnqiCMS website.

2025-11-08

How to quickly generate a customizable website guestbook form with the `guestbook` tag?

In website operation, interacting with visitors and collecting feedback is an important link to improve user experience and obtain valuable information, and the comment form is the core tool to achieve this goal.AnQiCMS (AnQiCMS) fully understands its importance and provides the `guestbook` tag for users, allowing you to easily and flexibly build a powerful and highly customizable website guestbook form.

2025-11-08

How to display the comment list and pagination on the article detail page with the `commentList` tag?

In AnQi CMS, the comment list on the article detail page is an important component for enhancing user interaction and content vitality.To naturally and smoothly display these comments and achieve a friendly pagination experience, we need to cleverly use the `commentList` and `pagination` template tags.Next, let's take a look at how to implement the display and pagination of comments on the article detail page.

2025-11-08

How to use the `stampToDate` tag to format a database timestamp into a readable date?

In website operation, we often encounter such situations: the time information stored in the database, such as the publication time of articles, the creation time of goods, etc., is often in the form of a series of numbers (timestamps).This string of numbers is clear to machines, but it has poor readability for us users.Imagine, if next to an article it displays '1678886400' instead of '2023/03/15', wouldn't that be a big discount in experience?AnQi CMS knows this and has provided a very practical template tag——`stampToDate`

2025-11-08

How `include`, `extends`, and `macro` tags enhance the reusability and maintainability of template code?

## Improving AnQi CMS template efficiency and maintainability: the clever use of `include`, `extends`, and `macro` In the daily content operation of AnQi CMS, we often need to create and manage a large number of pages.How to ensure that these pages maintain consistency while also being developed and maintained efficiently is a challenge that every operator has to face.

2025-11-08

How do `filters` (such as `truncatechars`, `safe`) format or sanitize the output content?

In the daily operation of AnQiCMS, the way content is presented and the security are the key factors that determine the professionalism and user experience of the website.AnQiCMS is a powerful template engine that draws many advantages from the Django template engine syntax, among which the 'filters' are the behind-the-scenes masters of content formatting and security processing.These filters can help us easily process output content, whether it is to simplify text, convert formats, or ensure the safety of the content, it becomes accessible.### Transformer: Content Output Transformer In simple terms

2025-11-08

How to render Markdown editor content correctly on the front-end page?

In AnQiCMS, Markdown is an efficient and widely popular content creation method.It uses a concise markup syntax, allowing creators to focus on the content itself without being troubled by complex layout tools.However, to present these concise Markdown texts to the user in the browser, it requires the collaborative processing of the AnQiCMS backend and the frontend template.Understanding this process can help you better utilize the content management capabilities of AnQiCMS, ensuring that your content is displayed in **status**.### Enable

2025-11-08