In AnQiCMS template development, we often need to flexibly display some small data sets according to business logic.These collections may be some custom tags, navigation items, or simply some status identifiers.Although AnQiCMS provides rich tags to call backend data, sometimes we want to define a small array directly in the template and loop through it to achieve finer control and more concise template code.

The template engine syntax of AnQiCMS is similar to Django, providing a straightforward and powerful way to operate data. When defining and using small arrays for looping in templates, variable assignment tags are mainly used.setand a very usefullistFilter, combinedforLoop tags, you can easily achieve this requirement.

Understand the variables and loop mechanism in AnQiCMS templates

AnQiCMS template variables are output through double curly braces{{ 变量名 }}While control structures, such as conditional judgment and loops, use single curly braces plus a percent sign{% 标签 %}The form. When we talk about loops, we usually refer to{% for item in collection %} ... {% endfor %}such a structure, which will iteratecollectioneach element in this collection, and access them within the loop body usingitemvariables.

The key here is how to generate this “collection”(set). In most cases,collectionMay come from the document list, category list, etc. passed from the background.But if we want to create a simple array on the fly in the template for iteration, we need some extra tricks.

Dynamically define small array variables:setTags andlistFilter

AnQiCMS template engine allows us to usesetThe label defines a variable in the template. Its basic syntax is{% set 变量名 = 值 %}The value can be the result of any expression.

To define an array, we can use it cleverlylistFilter.listThe filter can convert a string that conforms to the JSON array format into an array type that the template engine can recognize. CombinedsetLabels, we can define small arrays dynamically in templates.

For example, if you want to define an array containing several navigation names, you can do it like this:

{% set myNavItems = '["首页", "产品展示", "新闻中心", "联系我们"]'|list %}

In this line of code:

  • {% set myNavItems = ... %}We declared a variable namedmyNavItems.
  • '["首页", "产品展示", "新闻中心", "联系我们"]'This is a common string, but its content conforms to the format of a JSON array, that is, using square brackets[]enclosed, elements separated by commas,separated, string elements are enclosed in double quotes""Package.
  • |list:This islistFilter, it will parse this JSON formatted string into a real array object and assign it tomyNavItems.

This is,myNavItemsit becomes an array variable that can be used in subsequent templates.

Not only is it a simple array of strings, you can also define arrays containing complex data structures (such as objects), as long as they conform to the JSON format:

{% set productTypes = '[{"name": "电子产品", "code": "digital"}, {"name": "家居用品", "code": "home"}, {"name": "图书音像", "code": "books"}]'|list %}

Now,productTypesThe variable contains an array of three objects, each withnameandcodeproperties.

Apply the array variable to the loop: practical scenarios and techniques

Once we define a small array variable, we can apply it toforloop to achieve various flexible display requirements.

Scenario one: Generate a custom navigation menu or filter button

Assuming you want to display several fixed links in the sidebar and highlight the link corresponding to the current page.

{% set navItems = '[{"text": "首页", "path": "/"}, {"text": "关于我们", "path": "/about"}, {"text": "联系方式", "path": "/contact"}]'|list %}

<nav class="sidebar-nav">
    <ul>
    {% for item in navItems %}
        <li {% if url.Path == item.path %}class="active"{% endif %}>
            <a href="{{ item.path }}">{{ item.text }}</a>
        </li>
    {% endfor %}
    </ul>
</nav>

In this example,url.Pathis a global variable representing the URL path of the current page. By comparingitem.pathWithurl.Path, we can easily add the corresponding navigation item for the current page.activeClass, to implement highlighting effect.

Scene two: Dynamically generated status labels or marks

You may need to display a series of statuses or tags for some content, such as adding a tag cloud for articles on the article detail page, or adding attribute tags for products on the product list page.

{% set articleTags = '["网站优化", "内容营销", "SEO", "用户体验"]'|list %}

<div class="article-tags">
    <span>相关标签:</span>
    {% for tag in articleTags %}
        <a href="/tag/{{ tag }}" class="tag-badge tag-{{ forloop.Counter }}">{{ tag }}</a>
    {% endfor %}
</div>

Here we utilizedforloop.CounterThis built-in variable represents the current loop iteration count (starting from 1). By adding it to the CSS class name, you can achieve differentiated styling based on the index, for example,tag-1/tag-2etc.forLoops also provideforloop.Revcounter(Count down) and more built-in variables to control loop behavior, making template logic more flexible.

By this means, we can avoid creating a large amount of unnecessary data in the background, or avoid repeating the HTML structure in multiple template files, making the template code more concise and maintainable.

Summary

In AnQiCMS template, dynamically defining and using small array variables for looping is a very practical skill. By combiningsettags for variable assignment andlistThe filter converts JSON format strings to arrays, we can create any complex temporary data sets. Subsequently,forLoop tags and their built-in variables can easily iterate over these arrays, achieving flexible and diverse page display effects.This method not only enhances the flexibility and maintainability of the template, but also allows developers to complete content layout and interaction design more efficiently.


Common Questions (FAQ)

  1. Q:listCan the filter only handle strings? What if my array elements are numbers or boolean values?Answer: Yes,listThe filter expects a string as input.But the content of this string can contain various data types, such as numbers, boolean values, and even nested objects, as long as it conforms to the format of a JSON array.{% set mixedArray = '[1, "text", true, {"key": "value"}]'|list %}They are all fully supported.

2