How to split a comma-separated keyword string configured in the AnQiCMS backend into an iterable keyword list?

Calendar 👁️ 72

In the daily content operation of AnQiCMS (AnQiCMS), we often need to display related keywords on articles or product detail pages.These keywords not only help search engines understand the page content, but also guide users to discover more related information.In most cases, we will enter these keywords in a text box on the back-end, separated by commas, for example: 'website operation, SEO optimization, content marketing'.

However, when we want to display these keywords as independent, clickable tags or in a more visually appealing card format on the front-end page, the string directly obtained, such as "website operation, SEO optimization, content marketing", is not directly traversable.This requires us to process this string, splitting it into a list of independent keywords.

The powerful template engine and built-in filters of AnQi CMS make this task extremely simple and efficient.Next, we will discuss step by step how to cleverly convert the comma-separated keyword string configured on the backend into a keyword list that can be flexibly operated in the frontend template.

The entry of back-end keywords and front-end acquisition

In the Anqi CMS backend editing interface, for example, when adding or editing documents, we will fill in relevant terms in the "Document Keywords" field. According to the system prompts, multiple keywords are separated by English commas,Separate. This design is very suitable for content editing habits and convenient for backend management.

After the content is published, we can go through the front-end template.{{archive.Keywords}}(For the document detail page) or through the loop{{item.Keywords}}(For the document list) to obtain these keyword strings. At this point, what you get is a string of text, such as "website operation, SEO optimization, content marketing".

The solution is to utilizesplitFilter

To split this string of keywords into individual list items, the Anqi CMS template engine provides a powerful filter namedsplitas the name implies,splitThe filter can split a string into an array (or list) based on the specified delimiter.

Core idea:

  1. Get the keyword string set in the background.
  2. UsesplitFilter, separated by commas and possibly spaces, to split strings into multiple independent keywords.
  3. ByforLoop through this newly generated keyword list and display each keyword one by one.

Practical exercise: Implement the keyword list step by step.

Assuming we are editing a template for an article detail page and we want to display relevant keyword tags at the bottom of the article.

Step 1: Obtain the keyword string.

First, in your template file (for examplearchive/detail.htmlIn the middle, obtain the keyword string of the current article. For the convenience of subsequent operations, we can use{% set %}label to store it in a variable:

{% set raw_keywords = archive.Keywords %}

here,raw_keywordsIt will contain strings like 'website operation, SEO optimization, content marketing'.

Second step: usesplitFiltering is performed.

Next, we will usesplitfilter onraw_keywordsThe variable is being processed. Since users are accustomed to adding a space after a comma when entering keywords in the background, it is recommended to use,(a comma followed by a space) as a separator. If you are sure that the user only uses commas to separate, you can also only use,.

{% if raw_keywords %} {# 确保关键词不为空 #}
    {% set keyword_list = raw_keywords|split:", " %}
    {# 此时,keyword_list 将是一个包含 ["网站运营", "SEO优化", "内容营销"] 的数组 #}
{% endif %}

By this line of code,keyword_listNow it is an array that contains three independent string elements.

Step three: Traverse and display the keyword list

Nowkeyword_listarray, we can use{% for %}Loop through it and generate the HTML structure we want for each keyword, for example, displaying it as a label with a border and background color:

{% if keyword_list %}
    <div class="article-keywords">
        <span class="keywords-label">相关关键词:</span>
        {% for keyword in keyword_list %}
            {# 对每个关键词再次使用 `trim` 过滤器,去除可能存在的额外首尾空格,确保显示整洁 #}
            <a href="/search?q={{ keyword|trim }}" class="keyword-item">{{ keyword|trim }}</a>
        {% endfor %}
    </div>
{% endif %}

In this example, we add a simple CSS class to each keywordkeyword-itemTo facilitate style beautification. At the same time, in order to enhance user experience and SEO, we will wrap each keyword into a<a>the tag and use it.hrefThe property points to a search page so that the user can search for more related content when clicked.|trimThe use of the filter also further ensures the neatness of keyword display, avoiding abnormal display due to extra spaces entered during the background input.

Expanding Applications and Techniques

  • Style beautification:You can use CSS to add styles toarticle-keywordsandkeyword-itemclasses, such as background color, border, rounded corners, font size, etc., making keyword tags more prominent and beautiful.
  • Handling empty keyword:In the above example, we have{% if raw_keywords %}and{% if keyword_list %}made two judgments to ensure that only when keywords exist, the relevant HTML is rendered, to avoid unnecessary empty tags on the page.
  • Limit the number of displays:If there are too many keywords, you may want to only display the first few. You can useslicea filter to extract a part of the array:
    
    {% set limited_keywords = keyword_list|slice:":5" %} {# 只显示前5个关键词 #}
    {% for keyword in limited_keywords %}
        <a href="/search?q={{ keyword|trim }}" class="keyword-item">{{ keyword|trim }}</a>
    {% endfor %}
    

BysplitFlexible application of filters, users of Anqi CMS can easily convert pure text keywords from the background into elements with stronger interactivity and visual appeal on the frontend, greatly enriching the form of content presentation on the website and bringing a positive boost to SEO and user experience.


Frequently Asked Questions (FAQ)

Q1: If my keywords are not separated by commas and spaces, but only by commas,split:", "Can they still be split correctly?

A1: If your keywords are only separated by commas,separated, for example, 'website operation, SEO optimization, content marketing', then usesplit:", "It may not be split correctly because it expects a space after the comma. In this case, you should change the separator tosplit:","In order to maximize compatibility, you can split each keyword again|trimThis can remove any leading or trailing spaces that may exist in the keyword itself

Q2: How can I display only the first few keywords from the keyword list?

A2: You can usesliceUse a filter to truncate the keyword list. For example, if you want to display the first 5 keywords, you can...keyword_listApply to the variable|slice:":5". The complete code might look like this:{% set limited_keywords = keyword_list|slice:":5" %}Then you can iteratelimited_keywordsto display the first 5 keywords.

Q3: How to turn these split keywords into clickable links and jump to the built-in tag page or keyword library search page of Anqi CMS?

A3: Directly throughsplitKeywords split from the filter are plain text. If you want them to link to the official tag page or keyword search results of Anqi CMS, it is recommended to usetagListRetrieve the official tag list associated with the current article becausetagListEach tag object returned contains one that can be used directlyLinkattributes. For example:

{% tagList tags with itemId=archive.Id limit="10" %}
    {% for tag_item in tags %}
        <a href="{{tag_item.Link}}" class="keyword-item">{{tag_item.Title}}</a>
    {% endfor %}
{% endtagList %}

This method ensures the validity and correctness of the link

Related articles

How to use the `slice` filter to extract specific parts of parameters or paths from a long URL?

In the world of AnQi CMS templates, flexible data handling is the key to improving website user experience and SEO performance.Sometimes, we need to extract a specific part from a long URL, such as path parameters, product ID, or simply display a part of the URL to keep the page concise.At this time, the `slice` filter is an extremely useful tool that can help us accurately cut any segment of a string or array.

2025-11-07

Does the `slice` filter support negative indices to start cutting from the end?

In AnQi CMS template development, we often need to flexibly truncate and display strings or data lists, only showing a part of them.The `slice` filter is designed for this purpose, allowing us to precisely control the length of the content.And the answer to whether the `slice` filter supports negative indices, which is whether it can start cutting from the end, is affirmative, and this feature greatly enhances our flexibility and convenience when dealing with dynamic content templates.

2025-11-07

How to ensure the integrity of the sliced result when截取中文字符串 using the `slice` filter (to avoid half characters)?

In Anqi CMS template development, the `slice` filter is a commonly used tool for handling strings and arrays.It can help us conveniently extract a part of the content, whether it is several elements of a list or a specified segment of a long text.However, when it comes to cutting Chinese character strings, if you are not familiar with the underlying working principle, you may encounter a common and annoying problem: the cutting result appears as 'half a character' or garbage code.

2025-11-07

How to accurately slice an array in the AnQiCMS template?

During the template development process of AnQi CMS, we often need to flexibly handle the data displayed on the page, especially when the data is presented in the form of a list or sequence.Imagine that you are designing a product list page, where you need to select the top 5 most popular products from an array of dozens of products to display at the top of the page; or, you may need to truncate a long string from the content of an article detail page to use as a summary.

2025-11-07

What are the different splitting behaviors when the delimiter is empty or not present?

In AnQi CMS template development, the `split` filter is a very practical tool that can help us split strings into arrays according to the specified delimiter, which is very convenient when dealing with list data, tag content, or any structured text.However, when the delimiter is an empty string or does not exist in the target string, the behavior of the `split` filter shows some clever characteristics, understanding these characteristics is crucial for precise template control and avoiding potential errors.

2025-11-07

What are the main differences and application scenarios between the `make_list` filter and the `split` filter when splitting strings into arrays?

In AnQi CMS template development, it is often encountered that a string needs to be split into multiple parts for further processing or dynamic display.To meet this requirement, AnQiCMS template engine provides two very useful filters, `make_list` and `split`.Although they can both convert strings to arrays, there are obvious differences in their core functions, splitting logic, and applicable scenarios in actual use.Understanding these differences can help us handle content more efficiently and accurately.

2025-11-07

How to combine a dynamically generated array (such as a tag list) into a string with a specified delimiter for display in a template?

In website content operation, we often need to display a series of related information in the form of a list to users, such as all tags of an article, multiple characteristics of a product, or a set of image URLs.AnQiCMS's template system usually provides these data in the form of a dynamic array (or sometimes called slices, lists).

2025-11-07

How to use `split` and `join` filters to standardize user tag inputs?

In the daily content operation of AnQi CMS, the tags (Tag) submitted by users often face a common problem: the format is not unified.Some users are accustomed to separating with commas, some with semicolons, and even possibly with Chinese commas or even just spaces.These irregular inputs, if directly displayed on the website front-end, not only affect the aesthetics but may also reduce the usability of tags, for example, causing trouble when generating tag clouds or performing SEO optimization.

2025-11-07