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

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