The `length` filter calculates the length of Chinese string in an AnQi CMS template, is it counted by bytes or characters? How does it affect the output?

Calendar 👁️ 67

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:

  1. 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.
  2. Form input validationWhen users submit comments, messages, or registration information, the front-end often needs to limit the length of the input content. ThroughlengthA 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.
  3. 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.
  4. 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 }}
  • Ifarchive.TitleIs"安企CMS是一个强大的系统"The output will be11.
  • Ifarchive.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)

  1. Ask: If my string contains spaces and punctuationlengthWill 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.

  2. 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.

  3. 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.

Related articles

How to use the `get_digit` filter to extract a specific digit from a long numeric ID and display or perform logical operations in an Anqi CMS template?

In the development of Anqi CMS templates, we sometimes encounter situations where we need to extract a certain number of digits from a long numeric ID.For example, you may want to assign different styles to content based on some number of the ID, or make some logical judgments.At this time, the `get_digit` filter can be used.It provides a concise and efficient way to achieve this goal, making your template logic more flexible.

2025-11-08

In the Anqi CMS template, what is the difference between the `default` and `default_if_none` filters when the variable is `nil` or empty?

During the template creation process of AnQi CMS, flexibly using variables and their default values is the key to improving the robustness and user experience of the template.When you are dealing with a variable that may not exist (`nil`) or is empty, the `default` and `default_if_none` filters are the tools you commonly use.Although they can all provide an alternative output when the variable 'no value' occurs, their criteria for determining 'no value' are subtle and important.To understand the difference between the two

2025-11-08

The `stringformat` filter supports which formatting verbs in Go? How to choose the most suitable output format in AnQi CMS template?

In Anqi CMS template, the precise display of data is a key factor in improving user experience and website professionalism.The `stringformat` filter is exactly such a tool, allowing us to format various types of data in a highly flexible way to meet diverse front-end display requirements.It draws inspiration from the powerful `fmt.Sprintf` syntax in Go language, allowing developers and content operators to accurately control the format of the output content.###

2025-11-08

How to use the `stringformat` filter in Anqi CMS to output Go language struct data in a debug-friendly format (such as `%#v`) to the template?

During the template development process of Anqi CMS, understanding data structures is the foundation of efficient work.Especially when we need to debug complex Go language struct data, if we only use the conventional variable output method `{{ variable_name }}`, we can only see simple values, even memory addresses, which is not very helpful for understanding the overall picture of the data and locating problems.Fortunately, AnQi CMS provides a powerful `stringformat` filter,配合Go语言的 `%#v` formatting verb

2025-11-08

How to use the `length_is` filter in an Anqie CMS template to validate the length of user input or data lists and return a boolean value for conditional rendering?

In Anqi CMS template development, flexibly controlling the display method of content is the key to improving website user experience.Among them, the `length_is` filter is a very practical tool that can help us easily check the length of user input or data lists in templates and conditionally render based on the check results.The core function of the `length_is` filter is to determine whether the length of a variable (whether it is a string, array, or mapping) is equal to a predefined value.It does not directly return the specific length value

2025-11-08

How to use the `divisibleby` filter in AnQi CMS template to achieve alternate row coloring or group output every N elements?

In website operation, a well-designed page layout and content display can significantly improve user experience and readability.Especially in scenarios with a long list of items, if all entries are presented in the same style, it is easy to cause visual fatigue.At this time, alternating line colors or grouping by a specific quantity can well solve these problems.

2025-11-08

In addition to `stampToDate`, how can the `date` filter of Anqi CMS implement custom date and time formatting when handling `time.Time` type?

In Anqi CMS, the display of dates and times often needs to be adjusted flexibly according to the actual needs of the website.We all know that the `stampToDate` filter is very convenient for handling Unix timestamps, as it can easily convert a string of numeric timestamps into the date format we need.But sometimes, the date value we handle in the template may already be a `time.Time` type object in Go language, rather than the original timestamp.In this case, Anqi CMS provides another powerful tool, that is `date`

2025-11-08

How to format Unix timestamp to 'YYYY-MM-DD HH:MM' and other localized date strings using the `stampToDate` filter in AnQi CMS?

In website content management, the display of date and time information is ubiquitous.Whether it is the publication time of the article, the listing date of the product, or the submission time of the comments, a clear and readable date format is crucial for improving user experience.AnQiCMS (AnQiCMS) fully understands this need and provides powerful template tags and filters, among which the `stampToDate` filter is a powerful tool to convert the original Unix timestamp into a localized date string that we are familiar with.This article will delve into the usage of the `stampToDate` filter

2025-11-08