How to get the length of a string, array, or key-value pair in the `length` and `length_is` filters of the Anqi CMS template?

Calendar 👁️ 72

In AnQi CMS template development, it is often necessary to dynamically adjust the page display according to the length of the data content.Whether it is to truncate text, judge whether the list is empty, or perform simple content verification, understanding how to obtain the length of a string, array, or key-value pair is the foundation of realizing these functions.lengthandlength_isThese two filters, they can help developers flexibly handle these requirements.

lengthFilter: Get the actual length of the data content.

lengthA filter acts like a ruler, able to precisely tell you the 'size' of the content in the variable. Its usage is very intuitive, simply pass the variable through the pipe symbol|pass tolengththe filter.

String length calculationWhen applied to a string,lengthThe filter calculates the actual number of UTF-8 characters in a string.This means that, whether it is English letters, numbers, or Chinese characters, each character is counted as 1.This is particularly useful for websites that contain multilingual content, as it avoids the bias that may be caused by traditional byte length calculations.

For example, if you have a variableitem.TitleContaining "AnQiCMS", then{{ item.Title|length }}will output4. If the content is "AnQiCMS", it will output the same.7.

Array (Slice) and Map Length CalculationFor an array (also known as slice in Go language) or a map,lengthThe filter will return the number of elements or entries it contains. This allows us to easily know how many items a list has, or how many properties a data object has.

Suppose you have a variable namedtagsAn array variable that contains['网站运营', '模板开发', 'SEO']three elements, then{{ tags|length }}will output3. Similarly, if there is a key-value pairuser_info = {name: '张三', age: 30, city: '北京'}then{{ user_info|length }}will output3.

Usage example:

{# 假设有一个字符串变量 message = "欢迎使用安企CMS" #}
<p>消息内容的字符数:{{ message|length }}</p> {# 输出: 7 #}

{# 假设有一个数组变量 categories = ["新闻", "产品", "关于我们"] #}
<p>分类的数量:{{ categories|length }}</p> {# 输出: 3 #}

{# 假设有一个键值对变量 product_specs = {颜色: "红色", 尺寸: "L", 重量: "2kg"} #}
<p>产品参数的数量:{{ product_specs|length }}</p> {# 输出: 3 #}

length_isa filter: check the specified length of the data content

length_isFilter is onlengthBased on further development, it not only retrieves the length but also compares this length with a value specified by you and ultimately returns a boolean value (trueorfalseThis is very useful when precise length-based conditions need to be judged.

The working principle and limitations length_isBasic usage is{{ variable|length_is:期望长度 }}. It will checkvariablewhether the length of期望长度Please notelength_isThe filter is mainly designed for string variablesIf you try to apply it to a non-string variable (like a number), even if the length appears to match, it will returnfalse. This is a common misconception, developers should pay special attention when using it.

For example,{{ "hello"|length_is:5 }}will returntrueBut{{ 123|length_is:3 }}it will returnfalsebecause123Is a number, not a string. If you really need to judge the "length" of a number, you should convert it to a string first (although the Anqi CMS template engine does not have a directto_stringFilter, but usually in actual development, it is handled or avoided through other means, and direct comparison is not usually done).

Usage example:

{# 假设有一个字符串变量 username = "admin" #}
{% if username|length_is:5 %}
    <p>用户名长度正好是5个字符。</p> {# 输出: 用户名长度正好是5个字符。 #}
{% else %}
    <p>用户名长度不是5个字符。</p>
{% endif %}

{# 假设有一个字符串变量 description = "安企CMS是一个强大的内容管理系统。" #}
{% if description|length_is:15 %}
    <p>描述内容的字符数正好是15。</p>
{% else %}
    <p>描述内容的字符数不是15。</p> {# 输出: 描述内容的字符数不是15。 #}
{% endif %}

Application based on actual scenarios

These filters can play an important role in building dynamic and responsive website templates:

  1. Text truncation and hints:When the title or description of an article is too long, you can uselengthDetermine whether to truncate and combinetruncatecharsortruncatewordsFilter to display.

    {% set article_title = "安企CMS:为中小企业赋能的Go语言内容管理系统" %}
    {% if article_title|length > 20 %}
        <p>{{ article_title|truncatechars:20 }}...</p> {# 输出:安企CMS:为中小企业赋能的G... #}
    {% else %}
        <p>{{ article_title }}</p>
    {% endif %}
    
  2. Handling when the content is empty:When a list (such as links, image collection) may be empty, you can uselengthorlength_isJudge and display different content.

    {% commentList comments with archiveId=archive.Id type="list" limit="10" %}
        {% if comments|length_is:0 %} {# 或者 comments|length == 0 #}
            <p>目前还没有评论。</p>
        {% else %}
            <ul>
                {% for comment in comments %}
                    <li>{{ comment.UserName }}: {{ comment.Content }}</li>
                {% endfor %}
            </ul>
        {% endif %}
    {% endcommentList %}
    
  3. Dynamic styles or layout:Apply different CSS classes based on the number of elements in the list to achieve a more flexible page layout.

    {% categoryList categories with moduleId="1" parentId="0" %}
        {% if categories|length_is:1 %}
            <ul class="single-category-layout">
        {% elif categories|length > 5 %}
            <ul class="many-categories-layout">
        {% else %}
            <ul class="default-category-layout">
        {% endif %}
            {% for category in categories %}
                <li><a href="{{ category.Link }}">{{ category.Title }}</a></li>
            {% endfor %}
        </ul>
    {% endcategoryList %}
    

Masterlengthandlength_isThese simple yet powerful filters allow you to navigate effortlessly in the development of Anqin CMS templates, control the display of content more finely, and thus create more intelligent and user-friendly websites.

Frequently Asked Questions (FAQ)

1.lengthCan the filter correctly calculate the length of a string containing Chinese characters?Yes,lengthThe filter counts the length of a string by UTF-8 character count.This means that a Chinese character and an English character are both counted as 1, ensuring accurate length judgment for multi-language content.

2. Why{{ 5|length_is:1 }}This syntax will returnFalse? length_isThe filter is specifically designed for comparisonstringlength. When you try to apply it to a number (such as5It does not automatically convert the number '5' to the string '5' before performing the length comparison, but rather directly judges that the type does not meet the string requirement, therefore it returnsFalse. In uselength_isEnsure that you are operating on a string variable when

3. Besideslengthandlength_isWhat filters can help me handle string length or display limits?In addition to these two filters, Anqi CMS also providestruncatecharsandtruncatewordsfilter.truncatecharsUsed to truncate strings by character count and add an ellipsis at the end;truncatewordsIt is used to truncate strings by word count, and ellipses are also added. They are often used withlengthto avoid content overflow or enhance reading experience.

Related articles

How does the `join` filter concatenate elements of an array into a single string using a specified delimiter?

In Anqi CMS template design, we often encounter the need to integrate a series of data items into a coherent text.For example, we need to display multiple tags (Tag) in one place, or combine a set of custom parameter values obtained from the database.At this point, the `join` filter comes into play, which can efficiently concatenate the elements of an array into a string with the specified separator.### Understand `join`

2025-11-08

How do the `integer` and `float` filters convert strings to integers or floating-point numbers and handle conversion failure situations?

In web template development, flexible handling of data types is the key to ensuring correct content display.We often encounter situations where we need to convert string data obtained from databases or external interfaces into numbers for calculation or formatting display.AnQiCMS (AnQiCMS) fully considers this requirement, providing two built-in filters `integer` and `float` to help users easily convert strings to integers or floating-point numbers, and intelligently handle conversion failure cases, thereby enhancing the robustness of the template.

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

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 do the `linebreaks` and `linebreaksbr` filters convert newline characters in multi-line text to HTML's `<p>` or `<br/>` tags?

When managing content in Anqi CMS, we often encounter such situations: when the multi-line text entered in the background editing box is displayed on the front-end page, it becomes a single line, or the newline characters are displayed as text.This is because the browser ignores single newline characters (`\n`) by default when rendering HTML.If you want the content to be displayed with paragraph breaks or line breaks like in the editing box, you need to rely on the powerful template filters provided by AnQiCMS, especially `linebreaks` and `linebreaksbr`

2025-11-08

How does the `linenumbers` filter add line number markers to each line of multiline text?

In website content display, sometimes we need to add line numbers to specific multi-line text content, such as code examples, step-by-step tutorials, or log information, to enhance readability and facilitate reference.AnQiCMS provides a simple and practical template filter `linenumbers`, which can help us easily achieve this function. ### The `linenumbers` filter's purpose The `linenumbers` filter is specifically used to automatically add line number markers to each line of multi-line text.It will start from the number 1

2025-11-08

How to define a string array variable directly in the template using the `list` filter?

AnQiCMS with its flexible and powerful template engine, provides great convenience for content display.When using templates for front-end development, we often need to handle various data, among which array variables are a common and practical data structure.Most of the time, we may need to define some fixed or temporary string arrays directly in the template, rather than passing them through backend code each time.Fortunately, AnQiCMS provides a very convenient `list` filter, making this operation extremely simple.### Core Function Analysis: `list`

2025-11-08

How does the `phone2numeric` filter convert letters on a mobile phone's numeric keypad to the corresponding numbers?

In AnQiCMS template development, we often need to handle various data, and sometimes we may encounter some special situations with phone number input and display.For example, some phone numbers include letters (also known as "pretty numbers" or "vanity numbers", such as 1-800-FLOWERS) for ease of memorization or brand promotion.However, when dialing in practice, these letters need to be converted to the numbers on the corresponding number keypad.AnQiCMS provides a very practical built-in filter——`phone2numeric`, which helps us easily complete this conversion

2025-11-08