In the template development of Anqi CMS, 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 operation and template customization.lengthandlength_isThese practical filters help you better control the display of page content.
lengthFilters: A powerful tool for getting 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 powerful 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 a Chinese character and an English character are counted as one unit of length.For example, the length of "hello world - Array/slice:For data of list or array type,
lengthReturns the total number of elements contained. - Mapping/Dictionary:For data of key-value pair type,
lengthReturns the number of key-value pairs contained.
Example Usage:
Suppose you have a variablemessageContaining 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 on the article list page, or limit the number of characters in user comments.
- Content hint:When the list is empty, display the prompt 'No content available'; when the list elements are too many, display pagination or 'View more' button.
- Layout adjustment:Select different CSS styles based on the title length to avoid overly long titles from breaking the layout.
length_isFilter: Precisely judge whether the length matches
WithlengthFilter returns different length values directlylength_isThe filter is used to determine whether the length of a data is.equalsThe value you specified. 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 returnTrueotherwise, returnFalse. It is mainly used for the length judgment of strings, arrays, or mappings.
Example Usage:
If you need to check whether the user's input nickname is exactly 6 characters long, or whether a configuration item's array 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 input phone number is 11 digits long and if the password meets the minimum or fixed length requirements.
- Permission Control:Check if a certain user group has a specific number of permissions to decide whether to display a feature.
- UI logic:According to the number of elements in the specific data set, show or hide some UI elements, such as when the image list has only one image, the carousel control button is not displayed.
How to choose an appropriate filter?
ChooselengthOrlength_isIt mainly depends on your needs:
- If you need to get the specific length value of the dataFor example, displaying "A total of X records" on the page or using the length for subsequent mathematical operations
lengthThe filter is your first choice. - If you need to determine 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_isThe filter will make your code more concise and readable.
In the template development of AnQi CMS, although these two filters have similar functions, they have different focuses in different scenarios.Grasp their usage will enable you to handle dynamic content and implement complex logic more skillfully.
Common Questions (FAQ)
1.lengthDoes the filter have a difference in the way it calculates the length of Chinese and English strings?There is no difference.lengthThe filter treats its input as a sequence of UTF-8 encoded characters when calculating string length.This means that a Chinese character and an English character are both counted as 1 unit of length, rather than by the number of bytes.lengthAll will return the number of characters you see.
2.length_isCan a filter be used to judge the length of a number? For example, judge the number12345whether the length is 5?
length_isThe filter is mainly used to judge the length of strings, arrays, or mappings. If used directly on a numeric typelength_is, the result may not be as expected. For example{{ 12345|length_is:5 }}It may returnFalseIf you really need to judge the 'length' of a numeric value (i.e., its character count as a string), it is recommended to convert it to a string first