As a senior AnQi CMS website operations personnel, I know that flexible content presentation is crucial for attracting and retaining users. The powerful template engine of AnQiCMS, especially its conditional judgment (if)and loop traversal(for) Tags are the core tools for dynamic content rendering. They allow websites to maintain consistency in content structure while being able to flexibly display information based on data states and business logic.

The foundation of dynamic content rendering: Understanding AnQiCMS template tags

AnQiCMS uses a syntax similar to Django's template engine, allowing developers and operators to present backend data on the frontend in a concise and intuitive manner. All control flow tags, such as conditional judgments and loops, are used{% 标签名 参数 %}The format is defined and requires corresponding end tags{% end标签名 %}to close. The output of variables is through double curly braces{{ 变量名 }}To implement. Deeply understanding the application of these tags is the key to building a highly interactive and functional AnQiCMS website.

Conditional judgment: usingifTag implementation of content intelligent display

ifThe tag is the most basic logical control structure in AnQiCMS templates, which allows us to decide whether to display page content based on specific conditions.This allows the template to present personalized content based on different data states, user permissions, or page context.

ifBasic structure of tags include{% if 条件 %}/{% elif 其他条件 %}and{% else %}. EachiforelifBlock must be{% endif %}Label ends.The condition can be the existence check of a variable, numerical comparison, string comparison, or boolean value judgment.For example, we can determine if a document exists, if a list is empty, if a certain value is greater than a specific value, or if a user's attribute is true.

In practical applications,ifThe use of tags is very extensive. Suppose we need to display different prompt information on the article detail page according to the document ID, or to display the dropdown menu only if the content has subcategories.

{# 检查文档ID是否为10,显示特定内容 #}
{% if archive.Id == 10 %}
    <p>这是ID为10的特别推荐文章!</p>
{% elif archive.Id > 5 %}
    <p>这是一篇较新的文章。</p>
{% else %}
    <p>这是一篇普通文章。</p>
{% endif %}

{# 判断列表是否为空 #}
{% if categories %}
    <p>这里有分类内容。</p>
{% else %}
    <p>暂无分类数据。</p>
{% endif %}

{# 判断某个属性是否存在或为真 #}
{% if item.HasChildren %}
    <p>该分类包含子分类。</p>
{% else %}
    <p>该分类没有子分类。</p>
{% endif %}

It is worth noting that when negating boolean values, you can usenotkeywords such as{% if not item.IsCurrent %}. Use them flexiblyiftags, which can make the page logic clearer and the user experience smoother.

Loop traversal: useforTag efficient rendering of list data

forThe tag is the key used in AnQiCMS templates for iterating over collections (such as arrays, lists, or slices).It allows us to traverse each element in the dataset and generate the corresponding HTML structure, greatly enhancing the reusability of templates and the dynamic nature of content.

forThe basic syntax of tags is:{% for item in collection %}of whichcollectionIs the dataset to be traversed,itemIs the variable representing the current element in each iteration. The loop also needs to be{% endfor %}Tag closed.

AnQiCMS'forTags also provide some practical auxiliary functions:

  • forloopobject: Within the loop, you can access the current loop's metadata, such asforloopthe object accessing the current loop's metadata, for exampleforloop.Counter(current iteration count, starting from 1),forloop.Revcounter(From the current iteration count in reverse order of the total number). This is very useful when adding specific styles or logic to loop items.
  • reversedandsortedModifier: Can beforadded directly after the tag.reversedReverse traverse the collection or addsortedTraverse after sorting in the default order (usually ID or name).
  • emptyblockIf:forThe collection being traversed in a loop is empty, you can use{% empty %}Define the content to be displayed when there is no data, to avoid the page from being blank or displaying errors.

Suppose we need to display a list of multiple articles on a category page, we can use it like this.forTags:

{# 遍历文档列表 archives #}
{% archiveList archives with type="page" limit="10" %}
    {% for article in archives %}
        <div class="article-item {% if forloop.Counter == 1 %}featured{% endif %}">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
            <p>{{ article.Description }}</p>
            <span>发布日期: {{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
            <span>浏览量: {{ article.Views }}</span>
        </div>
    {% empty %}
        <p>抱歉,当前分类下没有可用的文章。</p>
    {% endfor %}
{% endarchiveList %}

This example shows,forloop.CounterUsed to add a class to the first article item,featuredname,emptyblock is in,archivesFriendly prompts are provided when the list is empty.

ifwithforThe combination application: Building complex views

In practical web development,ifandforLabels are often not used independently, but are nested and closely coordinated to achieve more complex business logic and page layout. By placingifstatements inforInside the loop, we can make a separate conditional judgment for each item in the loop; otherwise, usingifstatements to control whether to execute aforloop can avoid unnecessary rendering.

A common combination scenario is to display multi-level categories in the navigation menu. We can determine whether a first-level category contains subcategories while traversing it, and if it does, we can nest another one inside.forLoop to traverse and display second-level categories.

{# 遍历顶级分类,例如产品分类 #}
{% categoryList mainCategories with moduleId="2" parentId="0" %}
    <ul class="main-nav">
        {% for category in mainCategories %}
            <li {% if category.IsCurrent %}class="active"{% endif %}>
                <a href="{{ category.Link }}">{{ category.Title }}</a>
                {# 判断当前分类是否有子分类 #}
                {% if category.HasChildren %}
                    <ul class="sub-nav">
                        {# 遍历子分类 #}
                        {% categoryList subCategories with parentId=category.Id %}
                            {% for subCategory in subCategories %}
                                <li {% if subCategory.IsCurrent %}class="active"{% endif %}>
                                    <a href="{{ subCategory.Link }}">{{ subCategory.Title }}</a>
                                </li>
                            {% endfor %}
                        {% endcategoryList %}
                    </ul>
                {% endif %}
            </li>
        {% empty %}
            <li>暂无可用分类。</li>
        {% endfor %}
    </ul>
{% endcategoryList %}

In the example of the above navigation menu,{% if category.HasChildren %}Controls whether the submenu is rendered,<ul>structure, while the internal{% for subCategory in subCategories %}It is responsible for traversing and displaying specific sub-category items. This nested usage allows the template to handle complex data structures while maintaining clear and maintainable code.

Optimization and **practice** of template rendering

While usingifandforWhen tags render data, there are still some **practices** that can help us write more efficient and cleaner templates:

  • Use|safeFilterWhen the output content may contain HTML tags (such asarchive.Content), in order to avoid the browser automatically escaping and causing the tags to not be parsed, it should use|safeFilter, for example{{ article.Content|safe }}.
  • control spacing.:ifandforThe tag may introduce additional blank lines during rendering. To generate more compact HTML output, you can use a hyphen at the beginning or end of the tag.-For example{%- if condition %}or{% endfor -%}This will remove all whitespace on the corresponding side of the tag.
  • Variable definition and scope:{% with %}and{% set %}Tags allow temporary variables to be defined in templates. Although it is not direct.iforforBut they can help us store intermediate results, simplify complex conditional judgment or loop logic, especially inincludewhen passing specific variables in the template introduced,withthe tag is particularly applicable.
  • Multi-site compatibility: AnQiCMS supports multi-site management. When calling data tags, if you need to obtain data for a specific site, you can explicitly addsiteIdparameters, for example{% archiveList archives with siteId="2" %}.

By proficiencyifandforThese core template tags, combined with the other rich tags and practices provided by AnQiCMS, will enable you to build high-quality websites that are powerful, responsive, and easy to manage.


Frequently Asked Questions (FAQ)

1.forHow to judge whether the current item in a loop is the first or last item, and perform special processing?

You can useforloopto judge.forloop.CounterRepresents the current iteration count (starting from 1),forloop.LastIt is a boolean value indicating whether the current item is the last in the loop.

For example:

{% for item in archives %}
    <li {% if forloop.First %}class="first-item"{% endif %}
        {% if forloop.Last %}class="last-item"{% endif %}>
        {{ item.Title }}
    </li>
{% endfor %}

2. Why does myiforforalways appear extra blank lines around the tag? How can I eliminate them?

This is caused by the template engine retaining the white space around the control flow tags by default. To eliminate these extra blank lines, you can use a hyphen at the beginning or end of the tag.-Control spacing.

For example:

{# 消除 if 标签两侧的空行 #}
{%- if condition -%}
    <p>内容</p>
{%- endif -%}

{# 消除 for 标签每行末尾的空行 #}
{% for item in list -%}
    {{ item.Title }}
{%- endfor %}

3. How can Iforuse labels insideiftags to display different content or styles based on each loop item's properties?

You can directly useifNested in a tagforWithin a loop, for eachitemPerform conditional judgment.

For example, when displaying a list of articles, display different icons according to theFlagproperties (such as “recommended”) of the articles:

{% archiveList archives with type="list" limit="5" showFlag=true %}
    {% for article in archives %}
        <div>
            {% if "c" in article.Flag %} {# 假设 'c' 代表推荐 #}
                <span class="recommend-icon">★</span>
            {% endif %}
            <a href="{{ article.Link }}">{{ article.Title }}</a>
        </div>
    {% endfor %}
{% endarchiveList %}