How to split a string into an array by a specified separator and iterate and display it in the template in AnQiCMS?

Calendar 👁️ 84

In website operation and content management, we often encounter such scenarios: a certain field in the background stores multiple related information, such as multiple keywords of an article, various functional tags of a product, or multiple aliases of an author.This information is usually connected into a string by commas, semicolons, or other specific symbols.When it is necessary to display or style these pieces of information one by one in the front-end template of a website, it is necessary to split this string into independent items and traverse them one by one.

AnQiCMS provides a powerful and flexible template engine, whose syntax style is similar to Django, allowing us to use filters (Filters) to process data and iterate through loop tags (forLoop to traverse and display these processed data.

AnQiCMS template language basics

The AnQiCMS template system is designed to simplify the development process of content display. It makes data processing intuitive through the following core concepts:

  1. Variable output:Using double curly braces{{ 变量名 }}Display data passed from the backend to the template.
  2. Tags:Use single curly braces and percentages{% 标签名 %}To perform logical control, such as conditional judgment (if), loop (for) and so on.
  3. Filters (Filters):Using the vertical line|Symbol, it passes the value of a variable to a function for processing. Filters can change the format, content, or structure of data. This is the key to implementing string splitting.

Core function: split a string into an array

AnQiCMS provides several practical filters that can split strings into arrays (Go language slices) according to different rules for further processing in templates.

1.splitFilter: Split by specified delimiter

This is the most commonly used method, which can split a string into an array based on any delimiter you define.

  • Usage: {{ 字符串变量 | split:"分隔符" }}
  • Example:Suppose yourarchive.KeywordsThe field stores a string like "SEO optimization, content marketing, website operation", do you want to use a comma?,Split it.
    
    {% set keyword_string = archive.Keywords %}
    {% set keyword_array = keyword_string|split:"," %}
    {# 此时 keyword_array 就是一个包含 ["SEO优化", "内容营销", "网站运营"] 的数组 #}
    
    If the string does not contain the specified delimiter,splitThe filter will return an array containing a single element with the original string. For example, ifkeyword_stringis "SEO optimization", thenkeyword_string|split:","It will return["SEO优化"]. If the delimiter is an empty string"",splitThe filter will split each character of the original string into an element of the array.

2.make_listFilter: Split by character

When you need to split each character of a string (including Chinese, English, numbers, etc.) into an independent element in an array,make_listthe filter will be very convenient.

  • Usage: {{ 字符串变量 | make_list }}
  • Example:If you need to process a string like “Hello World” and want each Chinese character to be an independent element.
    
    {% set greeting_string = "你好世界" %}
    {% set char_array = greeting_string|make_list %}
    {# 此时 char_array 就是一个包含 ["你", "好", "世", "界"] 的数组 #}
    

3.fieldsFilter: Split by space.

This filter is specifically used to split strings into an array according to spaces (including consecutive spaces).

  • Usage: {{ 字符串变量 | fields }}
  • Example:If your string is “AnQiCMS is a GoLang CMS”, you want to split it by space.
    
    {% set phrase_string = "AnQiCMS is a GoLang CMS" %}
    {% set word_array = phrase_string|fields %}
    {# 此时 word_array 就是一个包含 ["AnQiCMS", "is", "a", "GoLang", "CMS"] 的数组 #}
    

Traverse and display the array in the template.

Once we have split the string into an array, we can use the AnQiCMS template engine toforloop tags to iterate over and display each element of the array.

  • Usage:
    
    {% for item in 数组变量 %}
        {# 在这里处理每个 item #}
    {% empty %}
        {# 如果数组为空,则显示这里的内容 #}
    {% endfor %}
    
  • loop variable:InforWithin the loop, you can useitemVariable (or any other custom variable name) to access the current element being traversed in the array. In addition, the template engine also provides some special loop state variables, such as:
    • forloop.Counter: The current loop count (starting from 1).
    • forloop.Revcounter: The remaining loop count.

Comprehensive example: Display the list of article keywords.

Let's look at a practical example, assuming the article detail page'sarchive.KeywordsThe field stores keywords separated by commas. We hope to display these keywords as tags at the bottom of the page, and each keyword should be a clickable link.

{# 假设 archive.Keywords 的值是 "SEO优化,内容营销,网站运营" #}
{% if archive.Keywords %}
    <div class="article-keywords">
        <strong>关键词:</strong>
        {% set keyword_array = archive.Keywords|split:"," %}
        {% for keyword in keyword_array %}
            <a href="/tags/{{ keyword|urlencode }}" class="tag-item">{{ keyword|trim }}</a>
        {% empty %}
            <span>暂无关键词</span>
        {% endfor %}
    </div>
{% endif %}

Code explanation:

  1. {% if archive.Keywords %}: First judgearchive.KeywordsThe field has a value, avoid displaying an empty area when there is no keyword.
  2. {% set keyword_array = archive.Keywords|split:"," %}: Use.setLabels willarchive.KeywordsString passed,Split and assign to a variable namedkeyword_arrayThe new variable. This is**practice, because it separates data processing and loop logic, making the code clearer.
  3. {% for keyword in keyword_array %}:Traversekeyword_arrayarray, each loop assigns the current element tokeywordVariable.
  4. <a href="/tags/{{ keyword|urlencode }}" class="tag-item">{{ keyword|trim }}</a>:
    • keyword|urlencodeEncode the keyword into a URL to prevent special characters from causing the link to fail.
    • keyword|trimRemove any spaces before or after the keyword to ensure a tidy display.
    • class="tag-item": You can apply custom CSS styles to each keyword.
  5. {% empty %}<span>暂无关键词</span>{% endfor %}If:keyword_arrayThe array is empty (i.e.,archive.KeywordsIt is an empty string or is split and still empty), then it shows 'No keywords available'.

By using such a combination, we can easily present the structured string data stored on the back-end in a beautiful and functional way on the website front-end.

Summary

AnQiCMS's template engine provides flexible filters and loops

Related articles

How can simple mathematical arithmetic operations be performed in the AnQiCMS template to display the result?

Handling arithmetic operations in AnQiCMS templates is an important link to the dynamic and personalized display of website data.No matter whether you need to calculate the total price of goods, display discount information, or make conditional judgments based on certain values, AnQiCMS's powerful template engine can provide flexible support.Thanks to its Django template engine features, simple mathematical arithmetic operations can be performed directly in the template without complex code logic.### Directly perform expression calculation in the template AnQiCMS template engine supports double braces `{{ }}`

2025-11-08

How to format a timestamp into the display format of "Year-Month-Day" in AnQiCMS?

In daily website operations, the display format of dates is crucial to user experience.A clear, consistent, and easy-to-understand date format that allows visitors to easily obtain information and enhance the professionalism of the website.For users of AnQiCMS, we often encounter data stored in the form of timestamps for content publishing time, update time, and so on. How to convert these long strings of numbers into a friendly display format such as 'Year-Month-Date' is an indispensable part of content presentation.

2025-11-08

How to safely extract strings or HTML content and add an ellipsis in AnQiCMS templates?

When operating a website, we often need to display article summaries, product descriptions, or user comments and the like.This text, if not processed, is displayed directly and completely. Long text may disrupt the page layout, affecting the overall aesthetics and information transmission efficiency.This is particularly important to truncate the content appropriately and add an ellipsis.AnQiCMS as an efficient and customizable content management system, its powerful template engine developed based on the Go language provides us with a simple and intelligent solution.Pass through built-in filters (filters)

2025-11-08

How to debug template in AnQiCMS and view the structure and value of variables (using dump filter)?

When developing website templates, we often encounter such confusion: what data does a variable in the template contain?What is its structure? What is the type? And what is the specific value?If these questions cannot be answered quickly, the debugging process will become extremely繁琐and time-consuming.Fortunately, AnQiCMS has provided us with a powerful and convenient debugging tool——`dump` filter, which can help us easily reveal the true face of variables.AnQiCMS developed in Go language, using a template engine syntax similar to Django

2025-11-08

How to remove specific characters or spaces from a string in AnQiCMS template?

In website content management, string processing is inevitable and crucial.In order to maintain the beauty of the page, keep the standardization of data output, or for SEO optimization, we often need to make fine adjustments to text content, such as removing extra spaces, punctuation marks, or other specific characters.AnQiCMS provides a flexible and powerful template engine, allowing us to easily implement these string operations in front-end templates.

2025-11-08

How does AnQiCMS determine if a string or array contains a specific keyword and display content accordingly?

In website operation, we often need to dynamically adjust the display of the page based on the specific attributes or keywords of the content.For example, when the article title includes the words 'latest', we may want to add a prominent 'NEW' label; or when a product description mentions 'Free Shipping', an icon showing free shipping should be automatically displayed.AnQiCMS (AnQiCMS) provides powerful template functions and rich filters, making it easy to meet these needs.

2025-11-08

How does AnQiCMS handle image resource management and optimization?

In the daily operation of websites, images are not only an important part of the content, but also a key factor affecting website performance and user experience.Efficient image resource management and optimization, can significantly improve website loading speed, improve search engine rankings, and effectively protect the copyright of original content.AnQiCMS is a system born for content operation, which provides comprehensive and practical functions in image processing to help us easily meet these challenges.### A comprehensive centralized management of image resources AnQiCMS provides a centralized management platform for image resources

2025-11-08

How to use AnQiCMS template tags to accurately control the display content of article detail pages?

The website is operational, and the article detail page is a key link for users to deeply interact with content and understand products or services.A well-designed, precise information presentation detail page, which can not only significantly improve user experience, but also effectively assist in SEO optimization.In such a flexible and efficient content management system as AnQiCMS, we can achieve fine-grained control over the content of article detail pages by ingeniously using its template tags.

2025-11-08