How does the `fields` filter split a single line string into an array of strings?

Calendar 👁️ 62

During the template development process of AnQi CMS, flexibly handling and displaying data is the key to enhancing website functionality and user experience.Sometimes, the content we get from the background may be a single line string containing multiple pieces of information, such as a list of keywords, product tags, or a set of feature descriptions.If you need to process or display this information as separate elements, for example, in the form of a list, we need a method to split this single string into multiple independent items.fieldsThe filter can be used.

What isfieldsFilter?

fieldsThe core function of the filter is that it can intelligently split a string containing spaces into an array of strings (commonly represented as an array in Go language)[]string{}This means that as long as your data items are separated by one or more spaces, this is the translation task for you.fieldsThe filter can help you parse them into individual elements, making it convenient to loop and display them in templates.

Why is it neededfieldsFilter?

In practical content operations, we may encounter the following scenarios,fieldsThe filter can effectively solve these problems:

  1. Keyword list display:The website background stores multiple keywords for articles in a certain field, separated by spaces.The front-end needs to render these keywords as separate tags, each of which can be clicked or have different styles.
  2. List of product features:A product has multiple features, and they are written in a field for convenience during backend entry, separated by spaces.The front-end needs to list these features one by one, with each feature taking up a line or an independent card.
  3. User input label processing:Allow users to enter custom tags in articles or product descriptions, and these tags are separated by spaces.In order to avoid directly displaying the original string, it is necessary to split them and present them in a standardized manner.

ByfieldsFilter, we can transform these seemingly unordered strings into structured data sets, thus enabling flexible style control and interactive design on the front end.

fieldsHow to use the filter

UsefieldsThe filter is very intuitive. Its basic usage is to pass a string variable or a direct string literal through a pipe operator|pass tofieldsThe filter. However, due tofieldsThe filter returns an array, we usually use{% set %}tags to store the result in a temporary variable for later iteration.

Assuming you have a string variablemyStringIts value is"安企CMS GoLang 内容管理 高效 灵活".

First, you need to pass this string throughfieldsfilter processing, and assign the result to a new variable, such astagList:

{% set myString = "安企CMS GoLang 内容管理 高效 灵活" %}
{% set tagList = myString|fields %}

Now,tagListwhich becomes a container that includes["安企CMS", "GoLang", "内容管理", "高效", "灵活"]This is a string array. You can verify its structure throughstringformata filter:

{{ tagList|stringformat:"%#v" }}
{# 显示结果可能是:[]string{"安企CMS", "GoLang", "内容管理", "高效", "灵活"} #}

Next, we can usefora loop tag to traversetagListRender each element and display it on the page.

<div class="tags-container">
    {% for tag in tagList %}
        <span class="tag-item">{{ tag }}</span>
    {% endfor %}
</div>

This code will generate the following HTML structure (the actual style depends on your CSS):

<div class="tags-container">
    <span class="tag-item">安企CMS</span>
    <span class="tag-item">GoLang</span>
    <span class="tag-item">内容管理</span>
    <span class="tag-item">高效</span>
    <span class="tag-item">灵活</span>
</div>

Using such a combination, we easily convert a string into a list element that can be independently operated and displayed.

Example of practical application: Dynamic keyword tags

Imagine a scenario, you need to display the key words of the article on the article detail page. There is a field in the background article informationarchive.Keywords, its value might be"网站运营 SEO 流量分析 内容营销".

In the template, you can use it like thisfieldsa filter to dynamically generate key word tags:

{% if archive.Keywords %}
    {% set keywordsArray = archive.Keywords|fields %}
    <div class="article-keywords">
        <strong>关键词:</strong>
        {% for keyword in keywordsArray %}
            <a href="/search?q={{ keyword|urlencode }}" class="keyword-tag">{{ keyword }}</a>
        {% endfor %}
    </div>
{% endif %}

This code first checksarchive.Keywordsif there is a value, then it splits it intokeywordsArray.Then, traverse this array to create clickable links for each keyword that point to the search results page of the website, and perform URL encoding on the keywords to ensure the correctness of the links.

Summary

fieldsThe filter is a simple yet very powerful tool in the Anqi CMS template engine, making it extremely efficient and convenient to process space-separated string data.By converting these strings into an iterable array, we can achieve more refined content display and interaction functions in the front-end template, thereby significantly enhancing the flexibility and user experience of the website.fieldsusing filters, which will bring more possibilities to the content operation of your Anqin CMS website.


Frequently Asked Questions (FAQ)

  1. Question:fieldsCan the filter also split strings using other symbols (such as commas, semicolons) instead of spaces?Answer:fieldsThe filter is specifically designed to split strings according tospacesSplit. If your string is connected with other delimiters (such as comma,or semicolon;), you should usesplitfilter.splitThe filter allows you to specify any delimiter, for example{{ myString|split:"," }}You can split a comma-separated string into an array.

  2. Question:fieldsWhat is the data type of the data obtained after splitting the filter, and what operations can I perform on it?Answer:fieldsThe filter splits to get a string array type ([]string{})。This means you can use{% for %}The loop tag can be used to iterate over each element of the array, you can also use other array-specific filters, such aslengthto get the length of the array,firstget the first element,lastget the last element, etc.

  3. Ask: If my string contains multiple consecutive spaces,fieldshow will the filter handle? For example,"安企 CMS 内容"what will it be split into?Answer:fieldsThe filter treats consecutive spaces as a delimiter and automatically removes empty strings. So, for"安企 CMS 内容"such a string, it will be split into["安企", "CMS", "内容"]Such an array containing three elements, which will not produce any extra empty string elements due to the two spaces in the middle.

Related articles

The `safe` filter in Anqi CMS template, when and why to use it to cancel the default escaping of HTML content?

Master the `safe` filter in AnQiCMS templates: unlock the correct rendering and safety boundaries of HTML content AnQiCMS, as an enterprise-level content management system based on Go language, adopts syntax similar to Django template engine in template design, which provides great flexibility for content display.When building website content, we often need to display the information edited on the backend on the front-end page.

2025-11-08

How to enable or disable automatic escaping for specific code blocks in templates using the `autoescape` tag?

In AnQi CMS template development, how to balance flexibility and security when handling dynamic content is an important consideration.Amongst, the HTML automatic escaping mechanism (`autoescape`) plays a key role, which is aimed at preventing cross-site scripting (XSS) attacks, while also allowing us to display native HTML content when needed.Understand and master the usage of the `autoescape` tag, which will make your template creation more skillful.Understanding automatic escaping

2025-11-08

What security escaping features do the `escape`, `e`, and `escapejs` filters provide when outputting HTML or JavaScript code?

It is crucial for the safety of output content in website operations.Especially when displaying user-submitted data or information obtained from external sources, if not properly processed, websites are easily vulnerable to cross-site scripting attacks (XSS) and other threats.AnQiCMS as a content management system that focuses on security, provides a powerful security escaping mechanism at the template rendering level, among which the `escape`, `e`, and `escapejs` filters are the key tools to ensure output security.AnQiCMS's template engine draws inspiration from Django

2025-11-08

How can the `dump` filter be used in the template development process for debugging and viewing the structure and value of variables?

During the development of Anqi CMS templates, we often need to handle various dynamic data.This data may come from a database, system configuration, or user input, and it is passed to the template as variables for display.However, sometimes the results displayed by the page are not what we expect-a field may be empty, the data format is incorrect, or the elements contained in a set may not be as expected.In this case, efficiently "viewing" the internal structure, type, and specific values of variables becomes the key to troubleshooting and speeding up development progress

2025-11-08

How do the `first` and `last` filters get the first or last element of a string or array?

In AnQi CMS template development, in order to display content more efficiently and flexibly, we often use various filters to process the data.These filters are like various tools in a toolbox that can help us quickly format, cut, or extract data.Today, let's talk about two very practical and intuitive filters: `first` and `last`, and how they help us easily obtain the first or last element of a string or array.### 1. Getting to know the `first` and `last` filters Imagine that

2025-11-08

How to precisely control the decimal place display of floating-point numbers using the `floatformat` filter, including positive and negative digit settings?

In website content operations, accurately displaying numbers, especially floating-point numbers, is often a key factor affecting user experience and data professionalism.It is crucial to ensure that numbers are presented consistently and legibly in product prices, statistical data, or scientific reports.AnQiCMS (AnQiCMS) is well aware of this need, providing a powerful `floatformat` filter in the template engine to allow content creators to flexibly control the display precision of floating-point numbers.### `floatformat` filter

2025-11-08

How does the `get_digit` filter retrieve a digit from a number at a specified position?

In the AnQi CMS template world, flexible handling and displaying data is a key link in content operation.When faced with the need to accurately extract a specific digit from a sequence of numbers, the `get_digit` filter is a very practical tool.It can help us achieve some detailed display requirements, such as grouping or highlighting based on the specific position of numbers. ### Core Function and Usage The main function of the `get_digit` filter, as the name implies, is to obtain a single digit from a number at a specific position.

2025-11-08

How does the `index` filter find the first occurrence of a keyword in a string or array?

In AnQi CMS template development, we often need to fine-tune the display of content, which includes flexible handling of string and array content.Understand and make good use of the various template filters provided by Anqi CMS, which can greatly enhance our ability to build dynamic and intelligent websites.Today, let's delve into a very practical filter——`index`, which can help us accurately locate the first occurrence of a keyword in a string or array.### `index` filter: A powerful tool for precise keyword positioning Imagine that

2025-11-08