How `length` and `length_is` filters are used to check the length of a string, array, or map?

Calendar 👁️ 72

In Anqi CMS template development, flexible handling and displaying data is the key to improving website interactivity and user experience.Understanding how to efficiently detect the length of strings, arrays, or mappings (similar to dictionaries or associative arrays in other programming languages) is the foundation for content operations and template customization.This article will introduce the Anqi CMS template engine in detaillengthandlength_isThese practical filters help you better control the display of page content.

lengthFilter: A tool to get the length of data

When you need to know how many characters a string has, or how many elements a list (array) contains, or how many key-value pairs a key-value pair (map) has, lengthThe filter is your helpful assistant. It can accurately return the length of the data, allowing you to make various logical judgments and content displays based on this information.

Working principle:

  • String: lengthThe filter calculates the actual number of characters in a string. It is worth noting that it calculates according to UTF-8 encoding, which means that both Chinese characters and English characters are counted as a single length unit.For example, the length of 'Hello World' is 4, while 'john doe' is 8.
  • Array/slice:For list or array type data,lengthReturn the total number of elements contained.
  • Mapping/dictionary:For data of key-value pair type,lengthReturn the number of key-value pairs contained.

Usage example:

Assuming you have a variablemessageStoring a piece of text, or aitemsarray.

{# 假设 message 变量值为 "欢迎使用安企CMS" #}
<p>消息长度:{{ message|length }}</p>

{# 假设 productList 变量为一个包含3个产品的数组 #}
{% set productList = ["产品A", "产品B", "产品C"] %}
<p>产品数量:{{ productList|length }}</p>

{# 假设 userData 变量为一个映射(map) #}
{% set userData = {"name": "张三", "age": 30} %}
<p>用户信息字段数量:{{ userData|length }}</p>

Actual application scenarios:

  • Word count:Display the word count of each article in the article list page, or limit the number of characters in user comments.
  • Content prompt:When the list is empty, display a prompt such as 'No content available'; when the list elements are too many, display pagination or 'See more' button.
  • Layout adjustment: Select different CSS styles based on the length of the title to avoid overlong titles from disrupting the layout.

length_isFilter: Precisely judge whether the length matches.

withlengthThe filter directly returns different length values,length_isThe filter is used to determine whether the length of a data item isequalsThe value you specify. Its return result is a boolean value (TrueorFalse) which is very suitable for precise length matching in conditional statements.

Working principle: length_isIt will get the length of the variable, then compare it with the target length you provide. If they are equal, it will returnTrue; otherwise, it returnsFalse. It is mainly used for the length judgment of strings, arrays, or mappings.

Usage example:

Assuming you need to check if the user's nickname is exactly 6 characters long, or if the array of a certain configuration item contains a specific number of sub-items.

{# 假设 userName 变量值为 "admin888" #}
<p>用户名为6个字符吗?{{ userName|length_is:6 }}</p> {# 返回 False #}

{# 假设 tags 变量值为 ["SEO", "CMS", "Go"] #}
{% set tags = ["SEO", "CMS", "Go"] %}
<p>标签数量是3个吗?{{ tags|length_is:3 }}</p> {# 返回 True #}

{# 假设 emptyList 变量为空数组 #}
{% set emptyList = [] %}
<p>列表为空吗?{{ emptyList|length_is:0 }}</p> {# 返回 True #}

Actual application scenarios:

  • Form validation:Verify if the user's input phone number is 11 digits long and if the password meets the minimum or fixed length requirements.
  • Permission control:Check if a user group has a specific number of permissions to decide whether to display a feature.
  • UI logic:Based on the number of elements in a specific data set, certain UI elements are displayed or hidden, for example, when the image list has only one image, the carousel control button is not displayed.

How to choose the appropriate filter?

SelectlengthOrlength_isIt mainly depends on your needs:

  • If you need to get the specific length of the dataFor example, displaying "Total X records" on the page, or using the length for subsequent mathematical operations, thenlengthThe filter is your preferred option.
  • If you need to judge whether the length of the data meets a specific conditionfor example, "if the length is equal to 10", and you want to get a boolean result directly for{% if %}the statement, thenlength_isFilters make your code more concise and readable.

In Anqi CMS template development, these two filters are similar in function, but have different focuses in different scenarios.Master their usage, and you will be more skilled in handling dynamic content and implementing complex logic.


Frequently Asked Questions (FAQ)

1.lengthDoes the filter have a difference in calculating the length of Chinese and English strings?No difference.lengthThe filter considers the string length to be a sequence of UTF-8 encoded characters when calculating.This means that a Chinese character and an English character are counted as 1 unit of length, rather than by the number of bytes.Therefore, whether it is a mix of Chinese and English,lengthIt will return the number of characters you see.

2.length_isCan the filter be used to determine the length of numbers? For example, to determine the length of numbers12345Is the length 5? length_isThe filter is mainly used to judge the length of strings, arrays, or mappings. If it is used directly on a numeric typelength_is, the result may not be as expected. For example{{ 12345|length_is:5 }}May returnFalseIf you indeed need to determine the 'length' of a numeric value (i.e., its character count as a string), it is recommended to convert it to a string first

Related articles

How `default` and `default_if_none` filters set a default display value for possibly empty variables?

In website content management, we often encounter situations where variable values may be empty.These empty values, if displayed directly on the front-end page, may lead to incomplete content display, page layout disorder, and even a bad user experience.AnQiCMS (AnQiCMS) as a powerful content management system, the Django template engine syntax it adopts provides us with a flexible way to handle such issues.

2025-11-07

How does the `add` filter work for adding numbers or concatenating strings in templates?

In AnQi CMS template design, we often need to perform some simple data processing, such as adding several numbers to display the total sum, or combining different text fragments into a complete sentence.At this time, the `add` filter is particularly convenient, as it is like a universal connector, capable of handling everything from arithmetic operations on numbers to the combination of text, making your template more flexible and dynamic.

2025-11-07

How do the `removetags` and `striptags` filters remove specific or all HTML tags from HTML content?

In Anqi CMS, when managing website content, we often encounter such situations: articles imported from outside, comments submitted by users, or code generated by rich text editors may contain various HTML tags.These tags are sometimes necessary, but more often, they may disrupt the page layout, introduce unnecessary styles, and even pose potential security risks. 幸运的是,AnQiCMS provides two very practical template filters —— `removetags` and `striptags`

2025-11-07

In which scenarios must the `safe` filter be used to prevent HTML content from being automatically escaped?

When using AnQiCMS for website content management and template development, we often encounter a problem related to HTML content display: Why does the rich text content I edit in the background display as a pile of original code with angle brackets on the front end, rather than a beautifully formatted effect?This is actually the "auto-escape" mechanism of AnQiCMS template engine at work, and to solve this problem, the `safe` filter has become the key tool we must master.### Why does automatic escaping occur? AnQiCMS

2025-11-07

The `contain` filter how to determine if a string or array contains a specified keyword?

In Anqi CMS template development, flexibly controlling the display of content is the key to improving website user experience and operational efficiency.Sometimes, we may need to determine whether a piece of text, a list (array), or a data object (Map/Struct) contains a specific keyword or property.At this time, the `contain` filter provided by Anqi CMS can give full play to its role, it can help us easily achieve this kind of conditional judgment, making the template logic more intelligent.What is the `contain` filter?

2025-11-07

How does the `count` filter count the occurrences of a specific keyword in a string or array?

In AnQi CMS template development, efficiently handling and analyzing content is the key to enhancing website interactivity and information display capabilities.Sometimes, we need to know how many times a specific word appears in a piece of text, or how many times a specific element is included in a data list.This is when the `count` filter comes into play.It is a very practical tool that can help us quickly count the occurrences of a specific keyword in a string or an array (slice).

2025-11-07

How does the `stringformat` filter output values of different data types in a custom format?

In the AnQiCMS template, mastering the format of data output is the key to content presentation.In order to display various data types (whether it is numbers, text, or more complex structures) in the way you expect to your visitors, AnQiCMS provides a powerful and practical tool - the `stringformat` filter.It is like a precise converter that can convert different types of values according to the rules you define, outputting neat and uniform strings.### Deep Understanding of `stringformat`

2025-11-07

How does the `thumb` filter quickly generate and display a thumbnail version of the original image URL?

In website operation, images are key elements to attract users and enrich content, but large image files often slow down page loading speed, affecting user experience and search engine optimization.Anqi CMS knows this and therefore provides a very convenient and efficient solution——the `thumb` filter.It can easily convert the original image into a thumbnail version suitable for web display, without manual processing, greatly enhancing the efficiency of content publication and the overall performance of the website.### Core Function Analysis: `thumb` Filter's Working Principle This is named

2025-11-07