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.Many times, we may need to define some fixed or temporary string arrays directly in the template, rather than passing them through backend code each time.Fortunately, AnQiCMS provides a very convenientlistThe filter makes this operation extremely simple.

Core function analysis:listThe role of the filter

listThe primary 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 a template. This means that you can convert text that looks like an array throughlistAfter filtering, we get a real array object, and then we can traverse and access it like we would with data obtained from the backend. According to the documentation, this filter will parse a string into a[]string{}An array of types, even if it contains numbers, they will be treated as strings after parsing.

How to use: I'll teach you step by step how to define an array

In AnQiCMS template, to define a string array variable, you need to combinesetTags andlistfilter.settags are used to declare and assign values to variables in the template, andlistThe 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 %}

Here are some key points to note:

  1. String format:listThe filter expects to receive a string formatted similar to a JSON array. This means you need to enclose the entire array content within single or double quotes, and array elements are placed within square brackets[and]between.
  2. Element separator: Elements within the array must be separated by English commas,It separates.
  3. Element referenceThe array elements (especially string elements) are best enclosed in single or double quotes, for example"关键词1". Although in some cases quotation marks can be omitted (such as numbers), it is recommended to always use them to maintain consistency and avoid potential parsing issues.
  4. setTag:yourArrayVariableThis is the variable name you define for this array, which will be used to refer to this array in subsequent template code.

Practice exercise: Applying in the templatelistFilter

Imagine you need to display a set of popular tags in the sidebar of a page, and these tags are not many and relatively fixed, or you need to test the display effect of a tag, at this timelistThe filter comes into play.

Let's 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 tags.
  • Then, we useforLoop throughmyTagsarray, for each element (tag) for processing.
  • In the link, to ensure the correctness of the URL parameters, we also usedurlencodeThe filter encoded the tag content.
  • The second example shows, even if the array contains numbers123AfterlistAfter the filter has processed,code|stringformat:"%T"It will also show its type asstringThis proveslistThe filter will uniformly handle all elements as 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, fixed list of items on the page (such as the friend link categories at the bottom of the website, some preset filtering conditions, etc).
  • Temporary data structureWhen performing some simple logical judgments or data combinations in the template, it is necessary to temporarily store a group of strings.
  • Template development debugging: In the early stages of developing the template, when the backend data is not ready, you can uselistthe filter to quickly simulate some data for testing page layout and loop 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.

Cautionary notes and **practice

  • Strict format: Make sure to pass inlistThe string of the filter strictly follows the format of a JSON array, otherwise it may cause parsing failure or unexpected results.
  • Type uniform:listThe filter will treat all parsed elements as strings. If your business logic has strict requirements for data types (such as performing mathematical operations), then these elements may need to be converted to the appropriate type when accessed (for example, usingintegerorfloatFilter, but it's best to handle the type on the backend).
  • Data volume limit:listThe filter is suitable for processing small-scale static data. For large amounts of dynamic data or data that requires complex queries, it is still recommended to retrieve and pass data to the template through the backend controller to ensure performance and code maintainability.
  • readability:Although 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.

MasterlistThe filter will make you more proficient in AnQiCMS template development, allowing you to flexibly deal with various front-end data display needs.


Frequently Asked Questions (FAQ)

  1. Q:listCan the filter-defined array 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 type. This means that even if you defined'["apple", 123, true]'|listaccessing123andtruein the template, they are still strings."123"and"true".

  2. Q: How do I traverselistWhat array is defined by the filter?A: After defining the array, you can traverse it like any other array or slice, using the AnQiCMS template engine providedforLoop the tag to iterate over it. For example:{% for item in yourArrayVariable %}{{ item }}{% endfor %}.

  3. Q:listWhat is the difference between a filter and the data retrieved from the database, which one 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.Data from the database is usually used to process large-scale, dynamically generated data that requires persistent storage.Choose which way depends on your data characteristics: if the data volume is small, fixed and does not need to be persisted,listThe filter is more convenient; otherwise, it should be obtained through the backend to access the database data.