In the template development of AnQi CMS,splitA filter is a very practical tool that can help us quickly split strings of a specific format into arrays. For example, we often store keywords, tags, or other attributes of articles in a field in the form of comma-separated values, and then display them when neededsplitProcess with the filter.
However, when usingsplitWhen filtering, there is a common situation that may cause us concern: that is, the sliced array may contain empty string elements.This usually occurs when there are consecutive delimiters in the original string (e.g., “keyword1,,keyword2”), or the string starts or ends with a delimiter (e.g., “,keyword1” or “keyword2,“).These empty strings are not only unattractive when displayed on the page, but they can also sometimes cause logical errors in data processing.
How can we elegantly filter out these empty string elements to ensure that we only get a clean and valid array?The powerful Django template engine syntax of AnQi CMS provides flexible solutions.
Identify the issue: Why does an empty string appear?
Imagine you have an 'associated word' field in an article, containing the following“安企CMS,内容运营,,模板制作,SEO,”. When you try to use|split:","The filter splits it when:
{% set raw_string = "安企CMS,内容运营,,模板制作,SEO," %}
{% set parts = raw_string|split:"," %}
{% comment %} 此时的 parts 数组可能是 ["安企CMS", "内容运营", "", "模板制作", "SEO", ""] {% endcomment %}
You will find that, because内容运营and模板制作There are two commas between them, as well as a comma at the end of the string, which causes two empty strings to appear in the array"". Directly traverse and display this array may cause extra empty content or separators on the page, affecting user experience.
Solution: CombineforLoop withifthe judgment.
In AnQi CMS templates, although there is no single filter directly for filtering empty elements in arrays, we can useforloop andifThe combination of logical judgments, easily achieving this goal.
The core idea is: first usesplitThe filter splits the string into the original array and then, while traversing this array, checks each element, processing only those that are not empty.
Here is a specific code example demonstrating how to operate:
{# 假设我们有一个变量 `archive.Keywords`,其值为 "安企CMS,内容运营,,模板制作,SEO," #}
{% set raw_keywords = archive.Keywords %}
{# 第一步:使用 split 过滤器将字符串切割成数组 #}
{% set keyword_list = raw_keywords|split:"," %}
<div class="keyword-tags">
{% for keyword in keyword_list %}
{# 第二步:在循环中判断当前元素是否为空字符串 #}
{% if keyword %}
{# 如果 keyword 不是空字符串,则进行展示或进一步处理 #}
<span class="tag">{{ keyword|trim }}</span>
{% endif %}
{% endfor %}
</div>
In this example:
- First, we will
archive.Keywordspass the value through|split:","a filter to cut into a namedkeyword_listarray. - Next, we use
{% for keyword in keyword_list %}Tag to traverse this array. - The most critical step is
{% if keyword %}. In Django template syntax, like an empty string""/0/falseornilsuch values are inifIt will always be evaluated as "False". Therefore,{% if keyword %}This line of code can effectively filter out all empty string elements, only whenkeywordWhen a variable has actual content, the code block inside it will be executed. - I also added an extra one.
|trimFilter. The advantage of this is that if there are extra spaces around a certain keyword in the original string (for example" 模板制作 ")trimThe filter can automatically remove these spaces, making the display cleaner.
By such a combination, we can ensure that only valid keywords are displayed on the page, avoiding display problems caused by empty strings. This method is intuitive and flexible, and can handle most processing needssplitThe scenario of the filter result.
Summary
In Anqi CMS, when you usesplitThe filter splits the string into an array and wants to remove any empty strings that may exist, the most direct and effective method is to useforLoop through the split array and within the loop, throughifscreen non-empty elements by judgment. This not only ensures the accurate display of content, but also improves the robustness of template data processing.
Frequently Asked Questions (FAQ)
Q1: If my original string contains spaces between delimiters (for example, "keyword1, keyword2"),splitthen usetrimCan the filter handle it?A1: Sure. When you use|split:","After splitting, if the element is like" 关键词2"such a string with leading or trailing spaces, then combine with|trimfor example, a filter (such as{{ keyword|trim }}) Can effectively remove these extra spaces to ensure that the final display of keywords is clean.
Q2: Besides empty strings, how can I filter out elements with specific content (such as 'meaningless'), for example?A2: With the same logic, you canifAdd more specific conditions to the judgment. For example, if you want to exclude elements with the value "meaningless", you can write it like this:{% if keyword and keyword != "无意义" %}. You can also combine|loweror|upperThe filter performs case-insensitive matching, for example{% if keyword and keyword|lower != "无意义" %}.
Q3: Is there a way tosplitremove consecutive delimiters before that, to reduce the generation of empty strings?A3: In some cases, you can try tosplitpreprocess the original string. For example, you can use|replaceThe filter replaces consecutive multiple delimiters with a single delimiter. For example,"关键词1,,,关键词2"|replace:",,,":","|replace:",,":","You can replace multiple commas with a single comma. But please note, multiplereplaceMay increase the complexity of template processing, usually, it is directly inforused in the loopifFiltering empty strings is already efficient and concise enough.