How to split a string into an array with a specified delimiter and iterate through it in AnQiCMS?

Calendar 👁️ 74

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.

Related articles

How to concatenate an array into a string with a specified delimiter for display in AnQiCMS?

AnQiCMS flexibly handles data in templates, which is the key to enhancing the website display effect for content operators.Among them, concatenating the array into a string with a specified separator is a common need to improve the readability and aesthetics of the content.Benefiting from the powerful and flexible template engine of AnQiCMS, especially its built-in rich filter functions, we can easily achieve this goal.

2025-11-08

How to determine if a variable exists or is empty in a template and display different default content based on the result?

During the development and maintenance of website templates, we often encounter situations where variables may not exist, have empty values, or do not meet expectations.If these variables are not properly handled, it may lead to page display anomalies, or even cause errors, affecting user experience.AnQiCMS (AnQiCMS) provides a powerful and flexible template engine based on Django syntax, allowing us to easily determine the state of variables and display different content accordingly.

2025-11-08

How AnQiCMS affects the display effect of the website under different template modes (adaptive, code adaptation, PC + mobile)?

When building and operating a website, we often consider how to make the website display beautifully on different devices.AnQiCMS (AnQiCMS) fully understands this point and therefore provides three flexible template modes to meet different needs: adaptive, code adaptation, and PC + mobile independent site mode.Each pattern has its unique implementation method and impact on the display effect of the website, understanding them can help us better choose the solution suitable for our project.### One, Adaptive Mode: One template, multiple screens Adaptive mode, as the name suggests

2025-11-08

How does AnQiCMS set the 'default thumbnail' to unify the display effect when images are missing?

In website content operation, images play a vital role. They can attract users' attention, enhance the visual appeal of the content, and help users quickly understand the theme of the content.However, in the process of daily content publishing, we sometimes encounter situations where some articles fail to upload exclusive thumbnails for various reasons, or the content itself does not have suitable images to extract.If the front-end page directly displays blank, broken image icons, or disordered layout, it will undoubtedly severely affect user experience and the professionalism of the website.To solve this problem, AnQiCMS

2025-11-08

How to display the current year or a custom time format in AnQiCMS templates?

In website operation, the accuracy and display of time information has a significant impact on user experience and content professionalism.Whether it is the copyright year in the footer or the publishing or updating time of the article content, a clear and consistent date format can enhance the overall perception of the website.AnQiCMS provides very flexible and powerful features in templates to meet these time display requirements.### Show the current year: Use the `{% now %}` tag to quickly display Many website footers display the current year as part of the copyright statement, for example “© 2023

2025-11-08

How to ensure that the custom system parameters set in the AnQiCMS backend can be correctly displayed in the frontend template?

The flexible application of custom system parameters in Anqi CMS is the key to improving website maintainability and operational efficiency.Many times, we may need some information that is not covered by the default system fields, such as specific external links, additional corporate honor information, or exclusive copywriting for a specific event.AnQi CMS provides a convenient way to add these custom parameters and ensures they are presented accurately in the front-end template.### One, understand the setting location of custom system parameters Firstly, we need to clarify the setting entry of custom system parameters in the Anqi CMS background

2025-11-08

How to customize structured data with Json-LD tags in AnQiCMS to optimize the display of search results?

AnQiCMS: Custom JSON-LD structured data, the secret weapon to light up search results In today's fiercely competitive information ocean, making our website content better understood and displayed by search engines is the key to improving online visibility.Structured data, especially JSON-LD, is playing an important role.It can help search engines accurately interpret page information, thereby presenting it in a more rich and attractive form in search results, which is what we commonly refer to as "Rich Snippets".AnQiCMS knows this

2025-11-08

How to implement line break and line number display for multi-line text in AnQiCMS template?

When using AnQiCMS to build websites, we often need to display multi-line text, such as article content, product feature descriptions, code snippets, or even comments.How to correctly implement line breaks for these multi-line text on the page, and further add line numbers for certain specific content (such as code), is the key to improving the reading experience.Luckyly, AnQiCMS's powerful template engine provides a very convenient solution, we can easily achieve these functions by using built-in filters.

2025-11-08