In the template design of AnQi CMS, we often encounter situations where we need to define and iterate over some fixed or small array data. Although most dynamic content is generated through built-in tags likearchiveList/categoryListGet it, but for some localization configurations, custom options, or static lists, processing arrays directly in the template will be more convenient. Anqi CMS provideslistfilters, in conjunction withforLoop tags, you can easily achieve this requirement.

KnowlistFilter: Array constructor in the template

listThe filter is a practical tool in the Auto CMS template engine, which allows us to directly convert a string-formatted array literal into a traversable array object.This is very useful for defining a fixed set of options, navigation item identifiers, or other short data lists in templates.

Its basic usage is to pass a string that conforms to the JSON array format to it, and then convert it through|listWe usually combinesetThe label will assign the converted array to a variable for later use.

For example, if we want to define an array containing several keywords in a template:

{% set myKeywords = '["安企CMS","模板","内容管理","GoLang"]'|list %}

In this code,'["安企CMS","模板","内容管理","GoLang"]'is a string,|listThe filter is responsible for parsing this string into a real array object and assigning it to a variable namedmyKeywordsIt is worth noting that even if the array contains values that look like numbers (such as'["item", 123, "another"]')listFilter also treats all its internal elements as string types during parsing.

UseforLoop: a general method to traverse an array

Once we have passed throughlistThe filter successfully defined an array variable, and can utilize the built-inforloop tags to iterate over each element.forLoops play a core role in Anqicms templates, they can iterate over any iterable object, including the array we just created.

a typicalforThe loop structure is as follows:

{% for item in myKeywords %}
    <!-- 在这里处理每一个 item -->
{% endfor %}

In each loop,itemThe variable will hold one element of the array at a time. You can use it directly.{{ item }}To output the value of the current element.

To better control and display the traversal process,forLoop also provides some practical auxiliary variables:

  • forloop.Counter: The current loop number, starting from 1.
  • forloop.Revcounter: Number of remaining elements not yet cycled.

In addition, when the array may be empty,forthe loop also has an elegantemptyA clause used to display specific content when the array has no elements, to avoid the page from being blank or showing errors:

{% for item in myKeywords %}
    <li class="keyword-item">第{{ forloop.Counter }}个关键词:{{ item }}</li>
{% empty %}
    <li>当前没有关键词可显示。</li>
{% endfor %}

Combine actual scenarios: make the template more flexible

Understoodlistfilters andforAfter the basic usage of loops, we can apply them in various practical scenarios, enhancing the flexibility and maintainability of the template.

For example, on a product detail page, you may need to display a fixed list of product features, which vary slightly between different product models but are not suitable for management through custom fields on the backend (because they are fixed options, not input values). In this case, you can define a feature array in the template:

{% set productFeatures = '["防水防尘", "超长续航", "高清显示屏"]'|list %}
<div class="product-features">
    <h3>核心功能</h3>
    <ul>
        {% for feature in productFeatures %}
            <li><i class="icon-check"></i> {{ feature }}</li>
        {% empty %}
            <li>暂无核心功能介绍。</li>
        {% endfor %}
    </ul>
</div>

Another common scenario is displaying social media link icons in the footer or sidebar of a web page. If you want these icons to be in a fixed order and type, and can be easily adjusted in the template,listFilter is very suitable:

{% set socialIcons = '["facebook", "twitter", "linkedin", "youtube"]'|list %}
<div class="social-media">
    {% for platform in socialIcons %}
        <a href="/{{ platform }}" target="_blank" title="访问我们的{{ platform }}主页">
            <i class="fab fa-{{ platform }}"></i>
        </a>
    {% endfor %}
</div>

Through this method, we can directly embed some lightweight, static data into the template, which enhances the template's self-sufficiency and reduces the dependence on backend dynamic data requests.

Tips

  • Data types are unified:As mentioned earlier,listThe filter will parse all elements as strings. If you need to perform mathematical operations on the "numbers" in the array, you need to use|integeror|floatFilter performs type conversion.
  • Scope of application: listThe filter is most suitable for defining lists with relatively fixed content and a small number of items. For large or frequently changing data, it is still recommended to use the backend content management function of the CMS and use the corresponding tags (such asarchiveList)to get.
  • Debugging Tips:In the development process, if you are not surelistwhether the filter correctly converts the string to an array, or want to view the actual content of the array, you can use|stringformat:"%#v"or|dumpFilter to print detailed information of variables, for example:{{ myKeywords|stringformat:"%#v" }}This will output the detailed structure of the array internally in the Go language, helping you debug.

Masterlistfilters andforThe combination of loops can help us build corporate CMS templates more efficiently and flexibly, handling various simple list data display needs.


Common Questions (FAQ)

  1. Question: ThroughlistDoes the array defined by the filter allow direct mathematical operations on elements if they are numbers? Answer:No.listThe filter will treat all array elements as string type. Even if you define like'["10", "20"]'|list,The array elements "10" and "20" are still strings. If you need to perform mathematical operations on these elements in a loop (such as addition or comparison), you must first use|integeror|floatThe filter explicitly converts them to numeric type, for example{{ item|integer }}.

  2. Q:listCan the filter be used to define nested arrays or more complex object structures? Answer: listThe filter is currently used mainly to convert simple string array literals to string arrays (i.e.,[]string{})。It does not support defining nested arrays directly (such as[['a','b'],['c','d']])or a complex object structure containing key-value pairs.For scenarios that require handling more complex data structures, it is usually recommended to process the data into the corresponding object or array form through the controller (backend), and then pass it as a template context variable for rendering.

  3. Q: If you go throughlistThe array defined by the filter is empty, will the page report an error? How can it be handled gracefully? Answer:If throughlistThe filter defined an empty array (for example)'[]'|list) and usedforLoop through, the page will not report an error. To provide a better user experience,forLoop tags provide a{% empty %}subordinate clause. Whenforthe array looped through is empty,{% empty %}and{% endfor %}The content between the tags will be rendered, you can use it to display prompts such as "No data" or "List is empty".