In AnQi CMS template development, dealing with string length is a common requirement.When content involves multilingual, especially including Chinese characters, whether the length of a string is calculated in bytes (byte) or characters (character) will directly affect the accuracy of template output and the presentation of content.
The AnQi CMS template is usedlengthThe filter is designed to solve this problem. When calculating the length of a string, it countscharacters instead of bytes.This means that whether it is a letter, number, or a Chinese character,lengththe filter will treat it as an independent "character" for counting.
The principle behind this, thanks to the unified adoption of Anqi CMS templatesUTF-8 encodingThe UTF-8 is a variable-length encoding, English characters usually occupy 1 byte, while Chinese characters may occupy 2 to 4 bytes. IflengthThe filter counts by bytes, so a string containing Chinese characters will have a "length" much larger than the number of characters we intuitively feel, which can lead to content truncation, layout disorder, and other issues.The AnQi CMS is developed based on the Go language, and the Go language operates on strings by using Unicode characters (which is what we usually understand as 'characters').Add the AanQi CMS template uses UTF-8 encoding, which makeslengthThe filter can accurately identify and count each independent character, whether it is English letters, numbers, or complex Chinese characters.
lengthThe practical application and impact of the filter
UnderstandlengthThe feature of filtering by character count is of great significance to our content operation and template design:
- Content truncation and abstract generation: When displaying a list of articles or summaries, we often need to truncate long titles or content to a fixed length. For example, if the requirement is that the title does not exceed 20 characters, use
{{ item.Title|length }}Ensure that the title, whether in Chinese or English, is precisely controlled within 20 characters to avoid incorrect truncation of Chinese titles or overflow of English titles. AccompanytruncatecharsFilters that can achieve more intelligent text truncation. - Form input validationWhen users submit comments, messages, or registration information, the front-end often needs to limit the length of the input content. Through
lengthA filter that can pre-validate user input on the client (or during backend template rendering) to ensure it meets database fields or design specifications, enhancing user experience and reducing invalid submissions. - Dynamic Layout and Style AdjustmentIn some complex layouts, it may be necessary to dynamically adjust the width, font size, or display method of elements based on text length.For example, if the text of a navigation menu item is too long, you can apply different CSS styles to ensure the page is beautiful.
- List and Array Processing: Besides strings,
lengthThe filter is also applicable for obtaining the number of elements in arrays and key-value pairs (map), which is very useful when traversing data lists, such as checking if an image list is empty or displaying a specified number of tags in a loop.
How to uselengthFilter
lengthThe filter usage is very intuitive and simple, just pass through the pipe symbol after the variable that needs to be calculated for length|AddlengthJust do it.
Example: Calculate the length of a stringSuppose there is a variablearchive.Title, its value could be"安企CMS是一个强大的系统"or"AnQiCMS is powerful".
{{ archive.Title|length }}
- If
archive.TitleIs"安企CMS是一个强大的系统"The output will be11. - If
archive.TitleIs"AnQiCMS is powerful"The output will be19.
It can be seen that Chinese characters and English characters are counted equally as 1.
Example: Calculate the length of an array or listAssumetagsIt is an array containing multiple tags, such as['SEO', '模板', 'Go语言'].
{{ tags|length }}
The output will be3.
Moreover, Anqi CMS also provideslength_isA filter used to calculate length while also determining if it equals a specified value and returning a boolean result.
{{ "你好世界"|length_is:4 }} {# 输出 True #}
{{ "你好世界"|length_is:5 }} {# 输出 False #}
Summary of the impact on content output.
lengthThe design of filter counting characters greatly simplifies the logic for handling the length of multilingual content, especially Chinese characters.It ensures that in the Anqi CMS template, regardless of the language of the content, the displayed character length is consistent with the user's intuitive perception and actual display length.This avoids display anomalies caused by underlying encoding differences, allowing content operators to focus more on the content itself rather than the technical details at the bottom, effectively improving the management efficiency and user experience of website content.
Frequently Asked Questions (FAQ)
Ask: If my string contains spaces and punctuation
lengthWill the filter count them?Answer: Yes, it will.lengthThe filter counts all visible characters in a string, including spaces, punctuation marks, numbers, English letters, and Chinese characters, as 1 character.Question:
lengthCan a filter be used to calculate the length of numeric or boolean values?Answer:lengthThe filter is mainly designed to calculate the length of strings, arrays (slices), and key-value pairs (maps).If applied to numbers or boolean values, it may yield unexpected results, even causing errors, as these types do not have the concept of 'length'.If you need to determine whether a numeric or boolean variable exists or is true, it is recommended to useifConditional judgment.If I need to process strings by byte length, does the Anqi CMS template have a corresponding filter?Answer: Anqi CMS'
lengthThe filter counts characters by Unicode rather than by bytes.The official documentation does not directly provide a filter for calculating the length of a string in bytes.Under most website content display scenarios, character counting is more in line with visual and layout needs.If there is indeed a special need for byte-wise processing, it may be necessary to preprocess data in the Go backend logic or consult more advanced template extension methods.