How to combine the `split` filter with the `if` logical judgment tag to perform different operations based on the cutting results?

Calendar 👁️ 77

In website content management, we often encounter a situation where a field stores a string of data separated by a specific symbol, and we need to perform different operations based on the results of the data being split.For example, an article tag field may store "SEO, operation, content marketing", or a product attribute field may store "color: red, size: L".The AnQi CMS template engine provides powerfulsplitFilters andifLogic judgment label, used together, it can very flexibly realize this requirement.

Get to knowsplitFilter: the tool for splitting strings

splitThe filter is a very practical tool used for string processing in the Anqi CMS template.The primary function is to split a string into an array using a specified delimiter (commonly referred to as 'slicing' or 'slice' in programming languages).

Its basic usage method is very intuitive:

{{ 你的字符串变量|split:"分隔符" }}

For example, if your article has oneTagsfield, the content is stored for"安企CMS,教程,模板":

{% set tag_string = archive.Tags %}
{% set tag_array = tag_string|split:"," %}
{# 此时 tag_array 会是一个包含 ["安企CMS", "教程", "模板"] 的数组 #}

It is noteworthy that if the specified delimiter does not exist in the string,splitThe filter will return an array containing the original string as the only element.If the delimiter is an empty string, it will split the string into an array by each character (including Chinese characters).

MasterifLogical judgment label: the core of conditional branching

ifLogical judgment tags are the basis for conditional control, which can decide whether to execute a specific template code block according to the truth value of the expression. Combinedelif(else if) andelseWe can build complex logical judgment processes.

The basic syntax structure is as follows:

{% if 条件1 %}
    {# 当条件1为真时执行的代码 #}
{% elif 条件2 %}
    {# 当条件1为假且条件2为真时执行的代码 #}
{% else %}
    {# 当所有条件都为假时执行的代码 #}
{% endif %}

Conditional expressions can be variables, comparison operations (such as==/>/</!=), logical operations (such asand/or/notOr other expressions that return boolean values (true/false).

splitwithifCombined strength: execute different operations according to the split results

Now, let's see how to convertsplitthe filter meetsifCombine logical judgment tags to achieve more refined content display. The key is,splitThe filter returns an array, we can use various properties of this array (such as length, whether it contains specific elements, etc.) to make conditional judgments.

Scenario one: Perform different operations based on the number of split elements

Suppose we have a custom fieldproduct.Benefits, storing the main advantages of the product, such as"高效,安全,稳定". We might want to:

  • If there is only one advantage, display it in bold letters.
  • If there are multiple advantages, display them in a list format.
  • If there are no advantages, display 'No features available'.
{% set benefits_str = product.Benefits|default:'' %} {# 先获取字段值,并设置默认空字符串以防nil #}

{%- if benefits_str|trim != '' %} {# 首先判断字符串是否有效,避免只有空格或空字符串导致误判 #}
    {% set benefits_array = benefits_str|split:"," %}

    {%- if benefits_array|length == 1 %}
        <p class="highlight-benefit">✨ {{ benefits_array[0]|trim }}</p>
    {%- elif benefits_array|length > 1 %}
        <ul class="benefits-list">
        {%- for benefit in benefits_array %}
            <li>✅ {{ benefit|trim }}</li>
        {%- endfor %}
        </ul>
    {%- else %} {# 理论上,如果benefits_str不为空,这里不会被触发,除非split返回空数组,但安企CMS的split不会 #}
        <p>暂无特色。</p>
    {%- endif %}
{%- else %}
    <p>暂无特色。</p>
{%- endif %}

In the code above, we first usetrimFilter clearedbenefits_strTrailing whitespace characters, then check if it is empty. Only when it is not empty, do the executionsplitOperation. Then, we getbenefits_array|lengthThe length of the array, and combineif/elif/elseTo determine different display methods.

Scenario two: Perform different operations based on whether the split contains a specific element

Assuming an article list page, each article may have onearticle.StatusField, content is"置顶,精选"or"精选"Or empty. We hope:

  • If the article is 'top', display a special icon before the title.
  • If the article is 'selected', add an eye-catching style to the title.

We can make use ofsplitSplit the status string into an array and then usecontaina filter to check if a specific status exists in the array.

{% for article in archives %}
    {% set status_str = article.Status|default:'' %}
    {% set status_array = status_str|split:"," %} {# 拆分状态字符串 #}

    <div class="article-item">
        {%- if status_array|contain:"置顶" %} {# 判断数组是否包含“置顶” #}
            <span class="icon-top">🔝</span>
        {%- endif %}

        <h3 class="article-title {% if status_array|contain:"精选" %}featured{% endif %}"> {# 判断是否包含“精选”,并添加样式 #}
            <a href="{{ article.Link }}">{{ article.Title }}</a>
        </h3>

        <p class="article-description">{{ article.Description }}</p>
        {# ... 其他文章内容 #}
    </div>
{% endfor %}

In this example, we perform operations on theStatusfield of each article'ssplitto getstatus_array. Then, twicecontainA filter (it can check if an array contains a specified value and returns a boolean value), it determines whether it contains 'Top' and 'Featured' to control the icon display and title style.

Scene three: Handling complex data structures, extracting and judging key information

Sometimes, the data structure in strings can be more complex, such as product configuration fieldsproduct.ConfigurationIt could be"CPU:i7-12700,RAM:16GB,SSD:512GB". We may need to extract the value of a specific configuration and make a judgment based on its value.

`twig {% set config_str = product.Configuration|default:” %} {% set config_items = config_str|split:“,” %} {# Split into [“CPU:i7-12700”, “RAM:16GB”, “SSD:512GB”] #} {% set cpu_model = “ %}

{%- for item

Related articles

`split` filter when splitting a numeric string, such as `"1_2_3_4"`, will the array elements remain as numeric type or string type?

When using AnQi CMS for website content management and template development, flexibly using built-in filters is the key to improving efficiency.Among them, the `split` filter is highly valued for its practicality in handling string splitting.Many users wonder when dealing with strings like `"1_2_3_4"` containing numbers, what type the array elements will be after splitting with the `split` filter.

2025-11-08

Does the `split` filter retain or remove HTML tags from a string containing HTML tags?

In the operation of daily websites, we often need to process the content obtained in various ways, such as cutting long text into short sentences, or extracting key information from a description.The Anqi CMS template engine provides a series of powerful filters to help us complete these tasks, among which the `split` filter is very commonly used.However, the content is often not just plain text; it may contain various HTML tags, such as paragraph tags `<p>`, bold tags `<b>`, link tags `<a>`, and so on.This raises a universally concerned issue

2025-11-08

The `split` filter in SEO optimization, what are the application scenarios for processing keyword strings (such as `"keyword1,keyword2,keyword3"`)?

In AnQiCMS content operation, we often encounter scenarios where we need to handle keyword strings, such as when setting multiple keywords for an article or product in the background, which is usually entered in the form of comma-separated, like `"keyword1, keyword2, keyword3"`.When these string data need to be displayed flexibly in the website front-end template or further processed, the `split` filter becomes a very practical tool.It can easily convert such strings into an actionable array, bringing multiple possibilities for SEO optimization.

2025-11-08

How to filter out empty string elements from an array split by the `split` filter?

In AnQi CMS template development, the `split` filter is a very practical tool that can help us quickly split a string of a specific format into an array.For example, we often store the keywords, tags, or other attributes of an article in a field in the form of comma-separated values, and then use the `split` filter to process them when displaying.

2025-11-08

Does the `split` filter affect the performance of template rendering when cutting large strings or complex data?

In website operations and template development, we often make use of the various powerful and flexible template filters provided by AnQiCMS to process data, among which the `split` filter is popular for its ability to easily split strings into arrays.However, when dealing with large strings or complex data structures, some users may wonder whether the `split` filter will affect the performance of template rendering.To deeply understand this problem, we first need to talk about the core technology stack of AnQiCMS.

2025-11-08

Do `split` filters have special considerations when processing data for different sites in the AnQiCMS multi-site environment?

Are there special considerations when the `split` filter processes data for different sites in the AnQiCMS multi-site environment?Under the multi-site management capability of AnQiCMS, we often need to display content and handle data between different sites.The `split` filter is a basic and powerful string processing tool in the template engine and is naturally used frequently.

2025-11-08

Can the `split` filter use tab or newline characters as delimiters, in addition to commas and spaces?

When using AnQi CMS for content management and template development, we often need to handle strings and split them into smaller data segments according to specific rules.The `split` filter is undoubtedly an important tool to achieve this goal.However, many friends may habitually think that `split` can only handle common separators such as commas, spaces, etc.Can tab characters and newline characters also be valid delimiters for the `split` filter?Today, let's delve into this topic in depth.

2025-11-08

How to get the first or last element of an array split by the `split` filter?

When managing content in AnQi CMS, we often encounter the need to process some text information stored in a specific format.For example, the keywords of an article are usually stored in a field in the form of a comma-separated string, such as 'AnQi CMS, content operation, template making'.When we want to highlight the most important keyword on the website front end, such as an article list or detail page, or to obtain the last keyword as a hint, we need to split these strings and extract the specific elements.

2025-11-08