How to iterate over an array defined in an AnQi CMS template using the `list` filter?

Calendar 👁️ 66

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

Get to knowlistFilter: The array constructor in the template.

listThe filter is a practical tool in Anqi CMS template engine, it allows us to directly convert a string literal array into an iterable array object.This is very useful for defining a fixed set of options, navigation item identifiers, or other short data lists in a template.

Its basic usage is to pass a string that conforms to the JSON array format to it, then through|listthe filter for conversion. Usually, we would combinesetThe transformed array will be assigned to a variable for subsequent use.

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

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

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

UseforLoop: The general method to traverse an array.

Once we pass throughlistThe filter successfully defined an array variable, which can then utilize the built-in template engine'sforloop tags to iterate over each element.forLoops play a core role in Anqi CMS templates, they can iterate over any traversable 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 to{{ item }}output the value of the current element.

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

  • forloop.Counter: The current loop iteration number, starting from 1.
  • forloop.Revcounter: The number of remaining elements to be looped over.

In addition, when the array may be empty,forThe loop also has an elegant way of doing things.emptyThe clause is used to display specific content when the array is empty, to avoid blank pages or 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 use of loops, we can apply them in various practical scenarios, enhancing the flexibility and maintainability of templates.

For example, on a product detail page, you may need to display a list of fixed product features, which vary slightly between different product models but are not suitable for management through backend custom fields (because they are fixed options rather than 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 the icons to be fixed in order and type, and easy to adjust in the template,listThe filter 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>

In this way, we can directly embed some lightweight, static data into the template, which improves the template's self-sufficiency and reduces the dependency on backend dynamic data requests.

Tip

  • Data types are unified:As mentioned before,listThe filter will parse all elements into strings. If you need to perform mathematical operations on the "numbers" in the array, you need to use|integeror|floatThe filter 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 Anqi CMS backend content management function to publish and manage, and to use the corresponding tags (such asarchiveList) to obtain.
  • Debugging tips:During development, if you are not surelistWhether the filter correctly converts a string to an array or want to view the actual content of the array, you can use|stringformat:"%#v"or|dumpA filter to print variable details, for example:{{ myKeywords|stringformat:"%#v" }}This will output the detailed structure of the array internally in Go language, helping you debug.

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


Frequently Asked Questions (FAQ)

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

  2. Question:listCan the filter be used to define nested arrays or more complex object structures? Answer: listThe filter is mainly used 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 requiring the processing of more complex data structures, it is usually recommended to pass the data as an object or array to the template through a controller (backend).

  3. Question: If throughlistDoes the array defined by the filter end up being empty, will the page report an error? How can it be handled elegantly? Answer:If it passeslistThe filter defines an empty array, for example'[]'|list),and useforLoop through, the page will not report an error. In order to provide a better user experience,forA loop tag provides a{% empty %}sentence. Whenforthe array to be looped through is empty,{% empty %}and{% endfor %}The content between the brackets will be rendered, you can use it to display prompts such as 'No data available' or 'List is empty'.

Related articles

Can 'list' filter be used to define an array that includes numeric types in the AnQi CMS template?

During the development of AnQi CMS templates, we often need to handle various data, among which arrays (or lists) are commonly used to organize data.When it comes to defining an array containing different data types directly in a template, many friends may be curious whether types like numbers can also be processed and included in the `list` filter?The answer is affirmative.The `list` filter in Anqi CMS template is designed to be very flexible, it fully supports including numeric data in the defined array.

2025-11-08

How to define a string array directly in the AnQi CMS template?

In AnQi CMS template development, we often encounter the need to display some list data on the page, such as navigation menus, category tags, or some fixed options.When this data is not suitable for dynamic retrieval from the backend database, or when we just need a simple and fixed set of strings, defining a string array directly in the template is very convenient and efficient.Our Anqi CMS provides a flexible way to handle such requirements based on the Django template engine syntax.

2025-11-08

How to display the name of a specified category

Flexible display of category names in AnQiCMS: A comprehensive template call guide Content categories are the core of the website structure, not only helping to organize and manage massive information, but also guiding users to browse the website and improve the user experience.Whether it is an article list, product details, or side navigation, clearly displaying category names can make the content of your website more organized.

2025-11-08

How to set pagination for a document list and display page navigation?

In modern website operations, setting up pagination for content lists is almost indispensable.It can not only significantly improve the user's browsing experience, avoid the slow loading caused by the long content of a single page, but also help search engines better crawl and index the website content.For friends using AnQi CMS, implementing pagination for the document list and displaying page navigation is a very intuitive and powerful feature.Our AnQi CMS provides flexible template tags, allowing full control over content display.To set pagination for the document list and display page navigation in a friendly manner

2025-11-08

How would AnQi CMS handle if the string format is incorrect when using the `list` filter to define an array?

In website content operation, we often need to display various list data in templates, such as a set of keywords, product features, or navigation links.AnQiCMS provides a powerful template engine, where the `list` filter is a very practical feature, allowing us to directly convert string-formatted data into an iterable array object in the template, greatly enhancing the flexibility of the template.

2025-11-08

How to split a string into an array using a specific delimiter in Anqi CMS template?

In the template development of AnQi CMS, we often encounter situations where we need to process specific strings.For example, a keyword of an article may be stored as a comma-separated string, and we want to display them as separate tags on the front end.At this point, splitting a string into an array with a specific delimiter becomes the key step in handling such issues.The AnQi CMS template engine supports syntax similar to Django, and it provides a rich set of filters (filters) to help us process data.

2025-11-08

How does the `split` filter split a string into an array of characters?

When using AnQiCMS for website content creation and template development, string processing is a common requirement.Sometimes, we need to split a complete string into smaller parts, such as breaking it down into an array of characters.This article will delve into the powerful `split` filter feature in AnQiCMS and provide practical examples.

2025-11-08

How to concatenate array elements in an Anqi CMS template with a custom character into a string?

In AnQi CMS template design, we often encounter situations where we need to display list-type data, such as multiple tags of an article, multiple image links on a product details page, or multiple options stored in a custom field.Directly outputting these array-shaped data to the page will often show a similar format like `["Label one", "Label two", "Label three"]`, which clearly does not meet the aesthetic and reading habits of users.At this point, we need to find a method to separate each element of the array with a custom character (such as a comma

2025-11-08