What is the difference between the `length` filter and the `length_is` filter in terms of content length judgment?

Calendar 👁️ 65

In AnQiCMS template design, we often need to judge or obtain the length of content in order to flexibly control the display of content.lengthFilters andlength_isThe filter is born for this purpose. Although they are all related to "length", in actual use, their functions and applicable scenarios have obvious differences.Understanding these subtle differences can help us build template logic more efficiently and accurately.

lengthFilter: Content Length "Counter"

lengthThe filter acts like a 'counter', its main function is to return the actual length of the specified content.This length is a specific number, which can be used directly for display, comparison, or other mathematical operations.

Its application range is relatively wide, not only can it calculate the number of characters in a string, but also the number of elements in an array (slice) or a key-value pair (map).

  • For string:lengthThe filter will calculate the actual number of characters in the string according to the UTF-8 encoding rules.This means that whether it is a letter, number, or Chinese character, it is considered as a character and counted in the total length.For example, the length of 'hello' is 5, and the length of 'hello world' is 4.
  • For the array (slice)It returns the total number of elements in the array.
  • For the key-value pair (map)It returns the total number of keys in the key-value pair.

Actual application scenarios:

lengthFilters are commonly used when you need to display content word count, limit loop iterations, or check if a list is empty, etc.

Usage example:

{# 获取字符串长度 #}
{% set myString = "安企CMS是一个强大的系统" %}
<p>字符串 "{{ myString }}" 的长度是:{{ myString|length }}</p> {# 输出: 11 #}

{% set anotherString = "Hello AnQiCMS" %}
<p>字符串 "{{ anotherString }}" 的长度是:{{ anotherString|length }}</p> {# 输出: 13 #}

{# 获取数组元素数量 #}
{% set myNumbers = [10, 20, 30, 40] %}
<p>数组中元素的数量是:{{ myNumbers|length }}</p> {# 输出: 4 #}

{# 获取键值对(map)键的数量 #}
{% set userInfo = {"name": "张三", "age": 30, "city": "北京"} %}
<p>键值对中键的数量是:{{ userInfo|length }}</p> {# 输出: 3 #}

{# 判断内容是否为空(字符串或数组) #}
{% set emptyContent = "" %}
{% if emptyContent|length == 0 %}
  <p>内容为空,可以显示提示信息。</p>
{% endif %}

{% set emptyList = [] %}
{% if emptyList|length == 0 %}
  <p>列表为空,可以显示“暂无数据”。</p>
{% endif %}

length_isFilter: Content length 'judge'

length_isThe filter is more like a 'judge', its role is to check whether the length of the content isexactly equal tothe number you specify. It does not return the specific length, but directly gives out 'yes' (TrueOr No (FalseBoolean result of it.

A very important restriction is, according to AnQiCMS design,length_isFilterCurrently it can only be used to judge the length of a string.And it requires the input to be a number. If you try to use it for a non-string type, or if the value being compared is not a number, it will not work as expected, which may cause errors or inaccurate results.

Actual application scenarios:

length_isThe filter is mainly used for strict length matching, such as requiring a certain input field to be a specific number of digits (such as a phone number must be 11 digits), or a title must reach a certain length to display a specific style, etc.

Usage example:

{# 判断字符串长度是否等于指定值 #}
{% set myCode = "AQCMS" %}
<p>字符串 "{{ myCode }}" 的长度是否是 5? {{ myCode|length_is:5 }}</p> {# 输出: True #}

{% set myText = "安企CMS" %}
<p>字符串 "{{ myText }}" 的长度是否是 4? {{ myText|length_is:4 }}</p> {# 输出: True #}
<p>字符串 "{{ myText }}" 的长度是否是 5? {{ myText|length_is:5 }}</p> {# 输出: False #}

{# 结合条件判断 #}
{% set productName = "高端定制网站开发服务" %}
{% if productName|length_is:10 %}
  <p>这个产品名称恰好是 10 个字符!</p>
{% else %}
  <p>这个产品名称的长度不是 10 个字符。</p>
{% endif %}

{# 错误示范(length_is 不能用于非字符串类型) #}
{% set myList = [1, 2, 3] %}
{# 下面的判断不会按预期工作,因为 length_is 仅用于字符串 #}
{# <p>列表长度是否是 3? {{ myList|length_is:3 }}</p> #}

Guide to Core Differences and Selection

In simple terms,lengthIt is a length_isIt is a "judge", which gives a "yes" or "no" boolean answer based on the preset value.

  1. Return type varies:
    • lengthReturn oneInteger(Actual length of content).
    • length_isReturn oneBoolean(TrueorFalse)
  2. Scope of application varies:
    • lengthCan be usedString, array, key-value pair.
    • length_is Can only be used for strings.
  3. Different emphasis on usage:
    • lengthFocus onObtain and useThe specific length of content (e.g., displaying word count, making size comparisons> <)
    • length_isFocus onPrecise judgmentDoes the length of content match a specific value (e.g., conditional judgment==)

When to uselengthFilter?

  • When you need to display the length of the content to the user (such as "Total 120 characters").
  • When you need to determine if a list or array is empty (myList|length == 0)
  • When you need to compare the length of content with other numbers (such asmyString|length > 100)

When to uselength_isFilter?

  • When you need to precisely determine whether the length of a string is exactly equal to a specific number (such asmyPhone|length_is:11)
  • When your logic depends on the exact length of a string, for example, when requiring that the user's input code must be 6 digits.

Understanding the subtle differences between these two filters can make us more skilled in AnQiCMS template development, writing more precise and logical code, thereby providing users with a better website experience.


Frequently Asked Questions (FAQ)

  1. Q:length_isCan the filter be used to determine the length of an array or list? A:According to the current design of the AnQiCMS template,length_isFilterIt can only be used to determine the length of a stringIf you need to determine the length of an array or list, you should uselengtha filter to get the length and then make a conditional judgment{% if myList|length == 5 %}to achieve.

  2. Q: How do I check if the length of a string is not equal to a certain value? A:You can uselengthThe filter gets the length of the string and then combines it with the template.ifLogical inequality operator. For example, to judgemyStringThe length is not equal to 10, you can write{% if myString|length != 10 %}. Althoughlength_isIt returns a boolean value, but it only judges equality, inequality is usually usedlengthCombine!=More flexible.

  3. Q:lengthDoes the filter count Chinese characters as one character per length in the calculation? A:Yes,lengthThe filter calculates the length of a string based on the actual character count in UTF-8 encoding.This means that whether it is a letter, number, or Chinese character, it is considered a character and counted in the total length. For example,"你好"The length is 2.

Related articles

How to count the character length of article titles, descriptions, or custom fields?

When managing content on AnQi CMS, we often need to pay attention to the character length of article titles, descriptions, or custom fields.This concerns not only SEO optimization, ensuring that the title and description are in line with the practices of search engines, but also affects the reading experience of users on the search results page or within the website's internal list.How can you easily count the character length of this content in Anqi CMS templates?The Anqi CMS built-in template engine provides many practical filters (filters), among which the `length` filter is our tool for counting character length

2025-11-08

What is the speciality of the `index` filter for Chinese position calculation when processing multi-language content?

## A clever approach: The unique features of `index` filter and Chinese position calculation in AnQi CMS multilingual content When managing multilingual content with AnQi CMS, the flexible use of its powerful template engine and rich filters can greatly improve content operation efficiency.Among them, the `index` filter is a very practical tool that helps us quickly locate the first occurrence of a specific substring in a string.However, when our content involves Chinese characters, the `index` filter has some unique behavior in position calculation.

2025-11-08

How to get the first occurrence position of a keyword in a string in AnQiCMS

In content operation, we often need to fine-tune and manage the text content on the website.In order to content review, dynamic display, or SEO optimization, sometimes we need to know the position of the first occurrence of a specific keyword in a text.AnQiCMS (AnQiCMS) is an efficient content management system that provides a convenient way to help us meet this need.Understanding the need: Why do we need to find the position of keywords?Understanding the position of keywords in strings is of great practical value in the process of content publishing and maintenance

2025-11-08

What role can the `contain` filter play in the context of sensitive word filtering?

In today's era where content is king, website operators are facing the dual challenge of actively publishing high-quality content while strictly controlling content security and compliance.Especially on platforms where user-generated content is increasing, how to efficiently and accurately filter sensitive words has become a key link in maintaining a healthy website ecosystem and protecting brand reputation.AnQiCMS (AnQiCMS) fully understands this need and provides many content security management functions, among which the `contain` filter can play a surprisingly practical role in the sensitive word filtering scenario.### The Foundation of Content Security

2025-11-08

How to get the number of elements in a list or key-value pair in AnQiCMS template?

AnQiCMS (AnQiCMS) makes website content display intuitive and efficient with its flexible template engine.In website operation, we often need to dynamically adjust the page layout, display different content, and even perform complex logical judgments based on the number of elements in a list or key-value pair (Map).Mastering how to obtain the number of these elements in a template is an indispensable skill for advanced customization and optimization.Luckyly, AnQiCMS template syntax provides a variety of convenient ways to help us achieve this goal.### Clever Utilization

2025-11-08

How to split a string containing multiple tags (such as “SEO, keywords, optimization”) into an array?

In the daily operation of Anqi CMS, we often encounter scenarios where we need to flexibly display some structured information in the content.For example, when setting keywords for articles or products, we may enter a string containing multiple tags in the "document keywords" field in the backend, such as Such strings are convenient to enter, but when displayed on the front end, we usually hope to display these tags separately, even to convert them into independent, clickable elements.How to convert such a comma-separated tag string

2025-11-08

What is the difference between the `split` filter and the `fields` filter when splitting strings by spaces?

During the template creation process in AnQi CMS, we often encounter scenarios where we need to split strings, such as extracting keywords from a description or parsing tag strings into independent words.AnQi CMS provides the practical filters `split` and `fields`. Although they can all split strings into arrays, there are subtle and crucial differences in their working methods and application scenarios when splitting strings by spaces.### `split` filter: The versatile separator expert `split` filter

2025-11-08

How to split a Chinese sentence into an array of single characters in AnQiCMS template?

In website content operation, sometimes we need to control Chinese text more finely, such as splitting a sentence into individual characters for display, or applying different styles, animation effects to each character.This need is particularly common when creating some special UI effects, interactive content, or even text games.How does the template system help us achieve this function when using AnQiCMS to build a website?AnQi CMS uses a template engine syntax similar to Django, which provides rich built-in tags and filters for content display

2025-11-08