In website operation, we often encounter the need to store some seemingly simple but actually containing multiple pieces of information in an article, a product description, or some custom field.For example, multiple tags of a blog, multiple features list of a product, or some words that need to be dynamically displayed.These data are usually connected into a long string with a specific delimiter (such as a comma, semicolon, or pipe).

When we need to split these strings on the front end of the website and display them one by one, or perform further style processing, AnQiCMS provides very intuitive and powerful template tags and filters that can help us easily achieve this goal.The AnQi CMS template engine has borrowed the syntax of Django, which is known for its simplicity and flexibility. Even if you are not familiar with complex programming languages, you can quickly get started.

Core operation:splitFilter splits the string

The Anqi CMS template engine provides a namedsplitThe powerful filter that can split a long string into an array of individual elements according to the delimiter you specify (usually called Slice in Go language).Once a string is converted to an array, we can conveniently traverse and display each element in the array.

Imagine we have a product model that contains a custom field calledproduct_featuresThis is used to store the core selling points of the product, for example, "waterproof, shockproof, high-definition camera, long battery life".We hope to list these features one by one on the product detail page, rather than displaying them as a pile of strings.

The entire process can be broken down into several simple steps:

  1. Get a string containing multiple pieces of information
  2. UsesplitThe filter splits the string into an array
  3. UseforLoop through the array and display each element

Let us demonstrate this process with a specific example:

Suppose your product detail template file (for example)product/detail.html needs to display these features.

Firstly, you need to obtain the details from the document.product_featuresThe value of this custom field. Anqi CMS providesarchiveDetailtags to obtain detailed information about the document, including custom fields:

{# 获取当前文档的自定义字段 'product_features' 的值 #}
{% archiveDetail productFeatures with name="product_features" %}

Here we assign the string we obtain to the template variableproductFeaturesIf your field does not contain these separated strings, and you are directly retrieving them from a database in list form, then you may skip directly.splitFilter. But it is necessary step for storing as a single string.

Next, we will usesplitfilter onproductFeaturesSplit a variable and store the results in a new variable, usually we would choose to use{% set %}labels to declare a temporary variable, which makes the code clearer:

{# 假设 productFeatures 的值是 "防水,防震,高清摄像头,长续航" #}
{% set featuresArray = productFeatures|split:"," %}

Now,featuresArrayIt has become an array containing four elements:["防水", "防震", "高清摄像头", "长续航"].

Finally, we can useforloop tags to iterate over this array and display each product feature:

<ul class="product-features-list">
    {% for feature in featuresArray %}
    <li>{{ feature|trim }}</li>
    {% endfor %}
</ul>

An extra one was also usedtrimFilter (|trim). This is a very practical detail, as users may add spaces before and after commas in their input, for example “waterproof, shockproof”.}]]trimThe filter can automatically remove any leading and trailing spaces from each element, ensuring a neat display.

Combine the above code snippet and you will see a neat list of product features on the product detail page:

<div class="product-info-section">
    <h3>产品特性</h3>
    {% archiveDetail productFeatures with name="product_features" %}
    {% if productFeatures %}
        {% set featuresArray = productFeatures|split:"," %}
        <ul class="product-features-list">
            {% for feature in featuresArray %}
            <li>{{ feature|trim }}</li>
            {% endfor %}
        </ul>
    {% else %}
        <p>暂无特性描述。</p>
    {% endif %}
</div>

By using such combinations, you can not only structure string content flexibly, but also display it beautifully according to actual needs.

Other practical skills

exceptsplitFilter, AnQi CMS also provides some related filters that can help in different scenarios:

  • make_listFilter:If you need to sort a string bya single characterCutting rather than by a specific delimiter, thenmake_listThe filter comes in handy. For example,{{ "安企CMS"|make_list }}You will get["安", "企", "C", "M", "S"]such an array. This is very useful in scenarios that require character-level operations.
  • joinFilter: joinThe filter issplitThe inverse operation. It can concatenate the elements of an array into a string using a specified separator. For example,{{ featuresArray|join:" | " }}It will recombine the just cut array into a string like 'Waterproof | Anti-shock | High-definition camera | Long battery life'.It is very convenient when you need to display the contents of the array in a certain format.

Summary

AnQi CMS with its flexible template engine and rich filters allows website operators to handle complex string data more efficiently and intuitively. Whether it's list information stored in custom fields or content that requires fine-grained control of display formats, throughsplitFilter combinationforLoop, we can all convert string data into clear, easy-to-manage, and display dynamic content, greatly enhancing the readability and user experience of the content.


Frequently Asked Questions (FAQ)

Q1: How to handle spaces before and after each element after string splitting?

A1:This is a common situation. In the above example, we have already taken this into account andforWithin the loop, for eachfeatureelement used|trimfilter.trimThe filter automatically removes spaces from both ends of the string, ensuring that each displayed feature is clean and tidy. For example," 防震 "after|trimWill be changed after processing"防震".

Q2: Besides custom fields, where else can you get strings to split and traverse?

A2:Of course you can. In addition to custom fields, many text contents of your website can be processed in a similar manner. For example:

  • Document content (archiveDetail.Content): If you insert a segment of text that needs special handling into the article or product content with a specific delimiter, you can first obtain the entireContentThen perform string operations on the required part.
  • System settings (systemLabel): If you add a custom parameter in the 'Global Feature Settings' back-end, its value is a string containing a delimiter, and it can also be{% system customVar with name="您的自定义参数名" %}obtained and split.
  • Contact information (contactLabel)Similarly, if a field in your contact information stores multiple entries (such as multiple phone numbers), it can also be split.

The key is to find the string variable you need to operate on and then apply the corresponding filter.

Q3: I can directlyforCut the string in the loop without using{% set %}?

A3:Theoretically, it is possible. For example, you can write it directly like this:

<ul class="product-features-list">
    {% for feature in productFeatures|split:"," %}
    <li>{{ feature|trim }}</li>
    {% endfor %}
</ul>

However, for the clarity and maintainability of the code, especially when dealing with more complex logic or nested loops, we recommend using first{% set %}Assign the sliced array to a new variable. This avoidsfora long expression at the head of the loop, making the code logic clear.