How to use logic tags such as if, for, etc. to process document data in AnQiCMS templates?

In the template world of AnQi CMS, building dynamic and responsive content displays that meet user needs is the core of website operation.As an experienced CMS operation person in information security, I know the importance of template logic tags.They give us the ability to render different content based on different data states, making the website not only beautiful but also smartly adapt to various business scenarios.ifandforUsing logical tags to process document data, thus creating web pages with rich hierarchy and interactivity.

Understanding the logic of AnQiCMS templates.

The template system of Anqi CMS has adopted the syntax of Django template engine, which allows web developers familiar with web development to get started quickly.The core is to distinguish variable output and logical control through specific markers.{{ 变量名 }}Performing reference, while all logical controls, such as conditional judgments and loops, are 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{% endfor %}This structure ensures the clarity and integrity of the template logic. In addition, the variable naming in the template usually follows camelCase naming convention, for example{{ item.Title }}or{{ category.Link }}.

ifLogical label: Selective display of content.

ifThe logic label 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 or which part of the content to display based on the truth or falsity of a certain condition.This is crucial when handling various dynamic content, such as displaying different information based on the user's status, or avoiding page errors based on the existence of data.

ifThe label 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 multiple mutually exclusive conditions, we can useelif[else if abbreviation] andelsetags to extendifstatements 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, showing different tags. IfFlagYes'h', show 'Headline'; if it is'c', show 'Recommended'; if not, show 'Normal'.

iftags support multiple comparison operators (==,!=,>,<,>=,<=),logical operator(&&,||,!),and member test(in,not in)。It can also intelligently handle the "true/falsenilValue, number0An empty array/slice is considered 'false'. For example, we can determine if a list is empty as follows:

{% 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 tags: a powerful tool for traversing data sets

forLoop tags are the key to handling data sets (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 for each element.

A basicforLoop syntax is{% for item in collection %} ... {% endfor %}Here,collectionThis is the array or slice you want to iterate over, anditemis 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 retrieve the latest 5 documents and toforLoop 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,forTags provide a gracefulemptyIf the block is empty,.collectionThere are no elements,emptyThe content within the block will be executed instead of the loop itself. This is more concise than using it alone.ifJudgment is more concise.

{% 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 %}

forLoop also provides some built-in loop variables to help us better control the loop process and element display:

  • forloop.Counter: The current number of times the loop is executed, starting from 1.
  • forloop.Revcounter: Remaining number of loop iterations.
  • forloop.First: True if it is the first element of the loop.
  • forloop.Last: True if it is the last element of the loop.

These variables are often associated withifCombine labels to apply 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 %}

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

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

ifandforcombination application: building complex page structures

In the actual operation of websites,ifandforTags are often collaborative to build complex, hierarchical content structures.For example, it 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 classification in the navigation and show the corresponding second-level classification below.If a first-level category does not have a second-level category, we would like to directly display the products under that first-level 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 demonstratescategoryListLabel gets the first-level category, then internally throughforTraverse each category. For each category, useif item.HasChildrenDetermine if there is a subcategory. If there is, use againcategoryListand nestedforLoop to display second-level categories; if not available, usearchiveListand anotherforLoop to display the product documents under the category. This step-by-step logic builds a highly dynamic and maintainable page structure.

Another common combination application is to process a collection of images in documents.Many documents may contain multiple images, usually stored in array form.ifTo ensure that the image is rendered only when it exists.<img>Label.

{% 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 get the document'sImagesfield (usually an array of image URLs), thenforLoop traversal.{% if img %}used to filter out possible empty image paths,{% empty %}then process the entireImagesempty array case.

Optimize template logic and **practice

When usingifandforWhen logical labels are encountered, adhering to some**practices can greatly enhance the performance and maintainability of the template.Firstly, try to keep the template logic 'lightweight'.The complex business logic and data preprocessing should be completed on the backend (controller or service layer), and the template is only responsible for receiving the processed data and displaying it.This makes the template more focused on its responsibilities, reducing the difficulty of debugging.

Secondly, make use of the security CMS providedextendsandincludeSupportive labels 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 and make modifications more centralized and efficient.extendsIt is used to define the page skeleton, allowing child pages to focus on filling specific content without rewriting the entire page structure.

Finally, note:{%- %}Such special syntax, they can remove the lines occupied by logical tags and the extraneous whitespace generated.This is very useful for generating neat HTML output, especially in scenarios that are sensitive to whitespace characters.-, it can accurately control the removal of whitespace:{%- if ... %}/{% endfor -%}.

Common Questions (FAQ)

1. How to debug templates in?iforforLogical problems?

An effective way to debug template logic in AnQi CMS is to use the 'print' variable method. Although the document does not explicitlydumporprintLabel, but you can check the value by directly outputting the variable to HTML. For example, inforthe loop, you can output{{ item }}to view the complete structure of each element, or output{{ forloop.Counter }}Track the number of loops. 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?

AnQiCMS template includes arithmetic operation tags, supporting basic addition, subtraction, multiplication, and division (+/-/*//)as well as the modulus operation(%),and they can be combined in expressions. For example,{{ 10 + 2 * 5 }}You will get20.It also supports floating-point arithmetic.However, for very complex calculations that require a large amount of data processing or logical judgment, we still recommend placing these logic on the backend, and passing the calculation results directly to the template for display.The primary responsibility of the template is to display data, not to handle complex business logic.

3. Why does myifcondition not work when checking if a variable is empty?

ifLabels will perform implicit conversion based on the type characteristics of the Go language when determining the 'true or false' of variables. For numeric types,0will be considered as false; for string types, an empty string""Would be considered false; for slices or arrays, an empty slice[]Would also be considered false; whereasnilvalues are considered false as well. If your variable seems to have a value butifthe judgment still