How to use if, for, etc. logic tags to process document data in the AnQiCMS template?

Calendar 👁️ 55

In the world of AnQi CMS templates, building dynamic and responsive content display that meets user needs is the core of website operation.As an experienced security CMS operator, I am well aware of the importance of template logic tags.They grant us the ability to render different content based on different data states, making the website not only beautiful but also intelligent in adapting to various business scenarios.Today, I will elaborate on how to skillfully use in AnQiCMS templateifandforUsing logical tags to process document data, thus creating a website page with rich hierarchy and interactivity.

Understanding the basic logic of AnQiCMS template.

The AnQi CMS template system adopts the syntax of the Django template engine, which allows web development personnel who are familiar with web development to quickly get started.The core lies in distinguishing variable output from logical control through specific tags.Variables are usually enclosed in double curly braces{{ 变量名 }}reference, while all logical control, such as conditional judgments and loops, is achieved through single curly braces with a percent sign{% 逻辑标签 %}Define. A key convention is that most logical tags need a clear end tag, such as{% if ... %}must end with{% endif %}End,{% for ... %}then it needs{% endfor %}This structure ensures the clarity and integrity of the template logic. In addition, the variable naming in the template usually follows camelCase, for example{{ item.Title }}or{{ category.Link }}.

ifLogical tag: To selectively display content

ifThe logic tag is the most basic and powerful conditional judgment tool in the template.It allows us to decide whether to display the content on the page based on the truth or falsity of a certain condition, or which part of the content to display.This is crucial when handling various dynamic content, such as displaying different information based on user status, or avoiding page errors when data exists.

ifThe tag provides several flexible syntax forms. The most direct way is{% if 条件 %} ... {% endif %}This will execute the middle code block when the condition is true.

{# 检查是否存在缩略图,如果存在则显示 #}
{% if archive.Thumb %}
    <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}" />
{% endif %}

When we need to make a choice among mutually exclusive conditions, we can useelif(short for else if) andelsetags to expandifstatements to form a more complex logical chain:

{% if archive.Flag == 'h' %}
    <span class="flag-headline">头条</span>
{% elif archive.Flag == 'c' %}
    <span class="flag-recommend">推荐</span>
{% else %}
    <span class="flag-normal">普通</span>
{% endif %}

In this example, we are based on the document'sFlagProperty value, display different tags. IfFlagIs'h'show "Top Story"; if it is'c'show "Recommendation"; if not, show "Normal".

iftags support various comparison operators (==,!=,>,<,>=,<=Logical operator (&&,||,!Member check (in,not in)。It can also intelligently handle the "true/false" judgment of various data types: non-empty strings, non-zero numbers, non-empty arrays, and objects are usually considered "true"; while empty strings,nilvalue, number0An empty array/slice is considered 'false'. For example, we can determine whether a list is empty in this way:

{% if archives %}
    {# 列表不为空,显示内容 #}
    ...
{% else %}
    {# 列表为空,显示提示信息 #}
    <p>暂时没有相关文档。</p>
{% endif %}

This judgment method is very practical when dealing with data lists, ensuring that the page can display information friendly even if there is no data.

forLoop tag: a powerful tool for traversing data collections

forThe loop tag is the key to handling data collections (such as document lists, category lists, image groups, etc).It allows us to iteratively access each element in the collection and render the corresponding template content.

A basicforLoop syntax is{% for item in collection %} ... {% endfor %}. Here,collectionThis is the array or slice you want to iterate over, whileitemis the temporary variable representing the current element in each iteration.

{% archiveList archives with type="list" limit="5" %}
    <ul>
        {% for item in archives %}
            <li>
                <a href="{{ item.Link }}">{{ item.Title }}</a>
                <p>{{ item.Description }}</p>
            </li>
        {% endfor %}
    </ul>
{% endarchiveList %}

This example shows how to usearchiveListtags to get the latest 5 documents and process throughforLoop through and display their titles and descriptions, and link to the detail page.

When you need to handle the case where the collection is empty,forThe tag provides an elegantemptyblock. IfcollectionThere are no elements in it,emptyThe content within the block will be executed instead of the loop itself. This is more concise than usingifjudgment alone.

{% archiveList archives with type="list" categoryId="1" limit="10" %}
    <ul>
        {% for item in archives %}
            <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
        {% empty %}
            <li>当前分类下没有文档。</li>
        {% endfor %}
    </ul>
{% endarchiveList %}

forThe loop also provides some built-in loop variables that can help us better control the loop process and element display:

  • forloop.Counter: The current loop count, starting from 1.
  • forloop.Revcounter: The remaining loop count.
  • forloop.First: If the current is the first element of the loop, it is true.
  • forloop.Last: If the current is the last element of the loop, it is true.

These variables are often associated withifUsing tags together, add unique styles or behaviors to specific elements in a loop:

{% navList navs %}
    <ul class="main-menu">
        {% for item in navs %}
            <li class="{% if forloop.First %}first-item{% endif %} {% if item.IsCurrent %}active{% endif %}">
                <a href="{{ item.Link }}">{{ item.Title }}</a>
                {# 假设这里还有二级菜单的判断和循环 #}
            </li>
        {% endfor %}
    </ul>
{% endnavList %}

Byforloop.FirstWe can easily add special styles to the first element of the navigation menu,item.IsCurrentIt can be used to determine whether the current menu item is selected.

forLoops also supportreversedandsortedA modifier used to change the iteration order:{% for item in archives reversed %}It will traverse the collection in reverse, while{% for item in archives sorted %}Will be sorted according to the default sorting rule (usually valid for numbers or strings).

ifandforCombination application: Building complex page structures

In the actual operation of the website,ifandforTags often work together to build complex and layered content structures.For example, this combination is especially common when building multi-level navigation menus or displaying lists of articles under categories.

Consider a multi-level product classification scenario, we hope to display the first-level category in the navigation and show the corresponding second-level category below it.If a primary category does not have a secondary category, we would like to directly display the products under the primary category.

{% categoryList productCategories with moduleId="2" parentId="0" %}
    <ul class="product-nav">
        {% for item in productCategories %}
            <li>
                <a href="{{ item.Link }}">{{ item.Title }}</a>
                {% if item.HasChildren %}
                    {# 如果有子分类,则循环显示子分类 #}
                    <ul class="sub-category-nav">
                        {% categoryList subCategories with parentId=item.Id %}
                            {% for inner in subCategories %}
                                <li><a href="{{ inner.Link }}">{{ inner.Title }}</a></li>
                            {% endfor %}
                        {% endcategoryList %}
                    </ul>
                {% else %}
                    {# 如果没有子分类,则直接显示该分类下的产品 #}
                    <ul class="products-list">
                        {% archiveList products with type="list" categoryId=item.Id limit="5" %}
                            {% for product in products %}
                                <li><a href="{{ product.Link }}">{{ product.Title }}</a></li>
                            {% endfor %}
                        {% endarchiveList %}
                    </ul>
                {% endif %}
            </li>
        {% endfor %}
    </ul>
{% endcategoryList %}

This example clearly demonstrates.categoryListTag to get the first-level category, then pass through internallyforLoop through each category. For each category, useif item.HasChildrenDetermine if there is a subcategory. If there is, use it againcategoryListand nestedforLoop to display the second-level category; if it does not exist, then usearchiveListand anotherforLoop to display the product documents under the category. This logical layering builds a highly dynamic and maintainable page structure.

Another common combination application is to handle a collection of document images.Many documents may contain multiple images, usually stored in an array.We can traverse these images on the document detail page and useifTo ensure that the image is rendered only when it exists.<img>.

{% archiveDetail archiveImages with name="Images" %}
    <div class="gallery">
        {% for img in archiveImages %}
            {% if img %} {# 再次确认图片URL非空 #}
                <img src="{{ img }}" alt="Gallery Image" class="responsive-img" />
            {% endif %}
        {% empty %}
            <p>该文档没有额外的图片。</p>
        {% endfor %}
    </div>
{% endarchiveDetail %}

Here we retrieve the document'sImagesfield (usually an array of image URLs), thenforlooped through.{% if img %}used to filter out possible empty image paths,{% empty %}then process the entireImagesThe array is empty.

optimize the template logic and **practice

While usingifandforWhen logic labels are applied, adhering to some practices can greatly improve the performance and maintainability of templates.First, try to keep the template logic "lightweight". Complex business logic and data preprocessing should be completed on the backend (controller or service layer), and the template is only responsible for receiving processed data and displaying it.This makes the template more focused on its responsibilities, reducing the difficulty of debugging.

Secondly, utilizing the Anqicms providedextendsandincludeauxiliary tags for template modularization. Abstract the common parts of the page (such as header, footer, sidebar) into independent template files, and throughincludeTag introduction can avoid code repetition, making modifications more centralized and efficient.extendsIt is used to define the page skeleton, allowing child pages to focus only on the filling of specific content without rewriting the entire page structure.

Finally, note{%- %}This special syntax can remove the lines occupied by logical tags and the extra blank characters generated.This is very useful for generating neat HTML output, especially in scenarios sensitive to whitespace.Add on both sides of the tag-to precisely control the removal of whitespace:{%- if ... %}/{% endfor -%}.

Frequently Asked Questions (FAQ)

1. How to debug in the templateiforforLogical issues?

An effective way to debug template logic in AnQi CMS is to use the 'print' variable method. Although the document does not explicitly specifydumporprintBut you can check the value of the variable by directly outputting it to HTML. For example, inforYou can output within the loop{{ item }}To view the complete structure of each element, or output{{ forloop.Counter }}Track the loop count. Forifconditions, you can add simple text outputsif/elifandelseinside the block, such as<div>条件A成立</div>To determine which branch is executed. If the issue is related to the data source, you need to check whether the backend data interface or business logic is returning data as expected.

2. Can complex mathematical calculations be performed in the AnQiCMS template?

The AnQiCMS template is built-in with arithmetic operation tags, supporting basic addition, subtraction, multiplication, and division (+/-/*//) and modulo operation (%), and can be combined in expressions. For example,{{ 10 + 2 * 5 }}You will get20It also supports floating-point arithmetic. However, for very complex calculations that require a lot of data processing or logical judgment, we still recommend placing this logic on the backend and passing the results directly to the template for display.The main responsibility of a template is to display data, not to handle complex business logic.

3. Why doesn't myifcondition work when checking if a variable is empty?

ifThe label will perform an implicit conversion based on the type characteristics of the Go language when judging the "true or false" of variables. For numeric types,0it is considered false; for string types, an empty string""Would be considered false; for slices or arrays, an empty slice[]Would be considered false; whilenilThe value would also be considered false. If your variable looks like it has a value butifthe judgment still

Related articles

How to filter sensitive words and ensure content safety in AnQiCMS documents?

As a senior CMS website operator for an information security company, I know the importance of content security for any website.It not only concerns user experience and brand reputation, but also the foundation for the legal and compliant operation of the website.AnQi CMS places content security at the core from the beginning, providing strong protection for website operators through a series of integrated functions, especially in terms of sensitive word filtering and content compliance.

2025-11-06

How to improve the loading speed of document pages by using AnQiCMS static cache?

As an experienced CMS website operation person, I am well aware of the importance of website loading speed for user experience and search engine optimization (SEO).In today's fast-paced online environment, users have extremely high expectations for website speed, any bit of delay can lead to visitor loss.AnQi CMS fully understands this, and its built-in static caching mechanism is a powerful weapon to solve this challenge. It can significantly improve the loading speed of document pages, bringing a smooth browsing experience to users.### AanQi CMS Static Cache

2025-11-06

How to use AnQiCMS permission control mechanism to manage document editing permissions?

As an experienced website operations manager, I fully understand the importance of an efficient and secure CMS system for content management.AnQiCMS with its flexible permission control mechanism provides strong support for managing document editing permissions, ensuring the standardization and security of the content production process. ### Core Mechanism of AnQiCMS Permission Control AnQiCMS has always regarded "flexible permission control mechanism" as one of its technical highlights since its design.The core of this mechanism lies in supporting 'admin group' and 'permission division'

2025-11-06

What benefits does the modular design of AnQiCMS have for document management extensibility?

As a website operator who is well-versed in the operation of AnQiCMS, I know that the core of whether a content management system can serve a company for a long time lies in its flexibility and scalability.The AnQi CMS adheres to the modular concept from its initial design, which is not only a consideration at the technical level but also a deep insight into the future development trends and actual needs of content management.The benefits of modular design for the extensibility of document management, in my opinion, are multifaceted and decisive.The modular design of AnQi CMS is first reflected in its flexible content model for the basic construction

2025-11-06

How to create a new document category in AnQi CMS?

As a website operator who deeply understands the operation of AnQiCMS, I know the importance of content organization for the success of the website.Document classification, as one of the core content management features of AnQiCMS, is the foundation for building a clear and efficient website structure.By reasonable classification, we can not only help users find the information they need quickly, but also lay a solid foundation for search engine optimization (SEO).Next, I will elaborate on the complete process of creating a document category in AnQiCMS.

2025-11-06

Can the content model of a document category be modified after its creation?

As a senior CMS website operation personnel in the security industry, I know that understanding data structures and content classification is crucial in content management.Regarding whether the content model of a document category can be modified after its creation, it is indeed a frequently questioned focus in daily operation.In the design philosophy of Anqi CMS, the association established between the content model and document classification is the core of system content organization.Once the document category is created and the content model it belongs to is specified, this association is fixed and cannot be directly modified.Specifically

2025-11-06

How to add a lower-level subcategory for document classification and manage its hierarchical relationship?

In AnQi CMS, efficient content categorization is not only the cornerstone of organizing website information, but also the key to improving user experience and search engine friendliness.As a website operator who is deeply familiar with the operation of Anqi CMS, I know that a logical and hierarchical classification system is crucial for content management and distribution.This article will detail how to add a lower-level subcategory for existing categories in Anqi CMS and effectively manage its hierarchy.### Build a clear content classification system In the Anqi CMS backend management interface, the content classification module is the core area for building the website information architecture

2025-11-06

How to set the SEO title and keywords of document classification to improve search engine visibility?

As an experienced security CMS website operator, I know that every detail can affect the website's performance in search engines.Content creation and optimization is my core responsibility, and the SEO settings of document classification are the key to improving search engine visibility, attracting target users, and ultimately促成 conversion.AnQiCMS provides many conveniences in terms of SEO, through reasonable configuration, we can fully utilize these features.

2025-11-06