AnQiCMS with its flexible and powerful template engine, provides great convenience for content display.When using templates for front-end development, we often need to handle various data, among which array variables are a common and practical data structure.很多时候,我们可能需要直接在模板中定义一些固定或临时使用的字符串数组,而不是每次都通过后台代码传递。listThe filter makes this operation extremely simple.

Core Function Analysis:listThe role of the filter

listThe main function of the filter is to convert a string that conforms to a specific format directly into an array variable that can be used in the template. This means that you can convert a text that looks like an array throughlistThe filter processes and gets a real array object, then it can be traversed and accessed like processing data obtained from the backend. According to the documentation, this filter will parse a string into[]string{}The array type, even if it contains numbers, will be treated as a string type after parsing.

Usage: Step-by-step guide to defining an array

In AnQiCMS template, defining a string array variable requires combiningsetTags andlistFilter.settags to declare and assign values to variables in the template, whilelistThe filter is responsible for converting the string we provide into an array.

The basic syntax structure is as follows:

{% set yourArrayVariable = '["元素1", "元素2", "元素3"]'|list %}

There are several key points to note:

  1. String format:listThe filter expects a string formatted like a JSON array. This means you need to enclose the entire array content with single or double quotes, and the array elements are placed within square brackets[and]between.
  2. element separator: Each element within the array must be separated by an English comma,Split the content.
  3. element reference:The array should wrap each element (especially string elements) with single or double quotes, for example"关键词1"Although quotes can be omitted in some cases (such as numbers), it is recommended to always use quotes to maintain consistency and avoid potential parsing issues.
  4. settags:yourArrayVariableThis is the variable name you define for this array, which will be used to refer to this array in subsequent template code.

Practical Exercise: Applying in the templatelistFilter

Imagine that you need to display a set of popular tags on the side panel of the page, and the number of these tags is not large and relatively fixed, or you need to test the display effect of a certain tag, at this timelistThe filter comes into play.

We will look at a real example:

{# 使用 list 过滤器定义一个名为 myTags 的字符串数组 #}
{% set myTags = '["安企CMS", "AnQiCMS", "模板技巧", "内容运营", "Go语言", "SEO优化"]'|list %}

<div class="tag-cloud">
    <h3>热门标签</h3>
    <ul>
        {# 遍历 myTags 数组,显示每个标签 #}
        {% for tag in myTags %}
            <li><a href="/search?q={{ tag|urlencode }}">{{ tag }}</a></li>
        {% endfor %}
    </ul>
</div>

<hr>

{# 另一个例子:包含数字的数组,但仍被视为字符串处理 #}
{% set productCodes = '["P-001", "P-002", 123, "P-004"]'|list %}
<p>产品代码列表及元素类型:</p>
<ul>
    {% for code in productCodes %}
        {# 即使定义时是数字,被 list 过滤器处理后,也会作为字符串处理 #}
        <li>{{ code }} (类型: {{ code|stringformat:"%T" }})</li>
    {% endfor %}
</ul>

In this example:

  • We first usesetTags andlistThe filter defines a namedmyTagsarray that contains several string labels.
  • Then, we useforto iteratemyTagsarray, processing each element (tag).
  • In the link, we also used to ensure the correctness of URL parameters.urlencodeThe filter encoded the tag content.
  • The second example shows, even if the array contains numbers123afterlistFilter processed,code|stringformat:"%T"It will also display its type asstring, which verifieslistThe filter unifies all elements into strings.

Application scenarios: When to uselistFilter?

listThe filter is powerful, but it is most suitable for specific application scenarios:

  • Fixed small list displayWhen you need to display a small number of fixed and unchangeable list items on the page (such as the category of friendship links at the bottom of the website, some preset filtering conditions, etc.).
  • Temporary data structureIn templates, when performing some simple logical judgments or data combinations, a group of strings needs to be temporarily stored.
  • Template development debuggingIn the early stage of template development, when the backend data is not ready, you can uselistfilters to quickly simulate some data for testing page layout and looping functions.
  • configuration options:Store a small amount of configuration options that do not need to be frequently changed through the database, such as some color codes, icon names, etc.

Attention Points and **Practice

  • Format strictly:Ensure that the input islistThe string of the filter strictly follows the format of JSON arrays, otherwise it may cause parsing failure or unexpected results.
  • Type uniformity:listThe filter will treat all parsed elements as strings. If your business logic has strict requirements for data types (such as needing to perform mathematical operations), then these elements may need additional type conversion when accessed (for example, usingintegerorfloatFilter, but it's better to handle the type on the backend).
  • Data volume limit:listThe filter is suitable for processing small-scale static data.For a large amount of dynamic data or data that requires complex queries, it is still recommended to retrieve and pass it to the template through the backend controller to ensure performance and code maintainability.
  • ReadabilityAlthough it is possible to define an array directly in the template, it is recommended to use this method only when the array content is short and does not involve complex logic, in order to maintain the template's cleanliness and readability.

MasterlistFilter, making it easier for you to develop AnQiCMS templates and flexibly handle various front-end data display requirements.


Common Questions (FAQ)

  1. Q:listCan the array defined by the filter contain different types of data (such as numbers, boolean values)?A: It can be included syntactically, butlistThe filter will parse all elements and treat them as string types. This means that even if you define'["apple", 123, true]'|listto access123andtruein the template, they are still strings"123"and"true".

  2. Q: How do I traverselistan array defined by a filter?A: After defining an array, you can traverse it like any other array or slice, using the AnQiCMS template engine providedforTranslate loop labels to iterate through them. For example:{% for item in yourArrayVariable %}{{ item }}{% endfor %}.

  3. Q:listWhat is the difference between filters and data obtained from the database, and which should I choose?A:listThe filter is mainly used to define and use small-scale, static string arrays directly in templates, such as fixed option lists or test data.While data is typically retrieved from a database for processing large-scale, dynamically generated, and persistent data storage.listThe filter is more convenient; otherwise, it should retrieve database data from the backend.