How to accurately calculate the length of a string containing Chinese, English, and special characters using the AnQiCMS `length` filter?

Calendar 👁️ 76

In website content management, precise control of string length is a seemingly minor but crucial aspect.It not only affects the display beauty of the content, but is also directly related to the search engine optimization (SEO) effect and user experience.lengthThe filter is a powerful assistant for calculating the length of a string.

UnderstandinglengthThe filter: More than just byte numbers.

The Anqi CMS template system uses a template engine syntax similar to Django, its built-inlengthThe filter demonstrates friendly characteristics in handling string length. Unlike some systems that simply calculate the number of bytes,lengthThe filter calculates based on UTF-8 encodingThe actual character countThis means that whether it is English, Chinese, Japanese, Korean, or various emoticons and special characters, each independent character is counted as '1' unit of length.

For example, one English character is counted as 1, one Chinese character is also counted as 1, and even a special symbol (such as an emoji 👋) is counted as 1.This design greatly simplifies the content management of multilingual websites, you need not worry about the display misalignment or truncation caused by inconsistent character encoding lengths between different languages.

Besides strings,lengthThe filter also applies to counting the number of elements in an array (slice) and a key-value pair (map), which is very convenient when dealing with lists or complex data structures.

Why is the exact length of a string so important?

  1. Search Engine Optimization (SEO)The search engine has a character length limit for the website's title (Title) and description (Description).If the limit is exceeded, the excess part may not be displayed, affecting the click-through rate.lengthThe filter can easily check and control the length of these key SEO elements, ensuring that the content is fully indexed and displayed.
  2. User Interface (UI) Design: On the front end of a website, article summaries, product names, navigation links, and other content are typically displayed within limited space.Precisely controlling the length can avoid text overflow, layout chaos, and ensure the page is tidy and beautiful.
  3. Data Validation: When users submit comments, messages, or other form data, the backend usually limits the length of the input content. Frontend useslengthThe filter can perform real-time verification, prompt users in time, and reduce invalid submissions.
  4. Content truncation and style adjustmentSometimes it is necessary to dynamically adjust the display style based on the length of the content, or automatically truncate overly long text and add ellipses (such as “… “).lengthThe filter is the foundation for achieving these dynamic effects.

How to use it in Anqi CMS templatelengthFilter?

lengthThe usage of the filter is very intuitive and concise, following{{ 变量 | 过滤器 }}the syntax structure.

Basic syntax: {{ 要计算长度的变量 | length }}

Actual example:

  1. Calculate the length of an English string:

    {% set english_text = "Hello AnQiCMS!" %}
    <p>英文文本长度:{{ english_text | length }}</p> {# 输出: 英文文本长度:14 #}
    
  2. Calculate the length of a Chinese string:

    {% set chinese_text = "你好安企CMS!" %}
    <p>中文文本长度:{{ chinese_text | length }}</p> {# 输出: 中文文本长度:7 #}
    
  3. Calculate the length of a string containing Chinese, English, and special characters:

    {% set mixed_text = "👋 你好 AnQiCMS 😊" %}
    <p>混合文本长度:{{ mixed_text | length }}</p> {# 输出: 混合文本长度:9 #}
    

    Here, emojis 👋 and 😊 are counted as a single character unit.

  4. Calculate the number of elements in an array (slice):

    {% set my_list = ["苹果", "香蕉", "橘子"] %}
    <p>列表元素数量:{{ my_list | length }}</p> {# 输出: 列表元素数量:3 #}
    
  5. Used in conditional statementslengthFilter:You can uselengthThe result of the filter is used{% if ... %}in the statement for conditional judgment. For example, to judge whether the title of the article is too long:

    {% archiveDetail article with name="Title" %}
    {% if article.Title | length > 30 %}
        <h1 class="long-title">{{ article.Title }}</h1>
    {% else %}
        <h1>{{ article.Title }}</h1>
    {% endif %}
    
  6. CombinetruncatecharsThe filter is used:Consider using atruncatecharsfilter. It handles truncation and adds an ellipsis directly, usually better than manual judgmentlengthIt is more convenient to cut later.

    {% archiveDetail article_desc with name="Description" %}
    <p>文章摘要:{{ article_desc | truncatechars:100 }}</p>
    

    Heretruncatechars:100It ensures that the text displays a maximum of 100 characters (including ellipsis) and supports the correct counting of UTF-8 characters.

Uselength_isThe filter makes precise judgments.

If you need to determine whether the length of a string, array, or key-value pair isexactly equal toa specific value, in addition to{{ 变量 | length == 某个值 }}the following, Anqi CMS also provideslength_isA filter that returns a boolean value (True or False) directly, making the code more concise.

Syntax: {{ 要计算长度的变量 | length_is:期望的长度值 }}

Example:

{% set content_string = "安企CMS" %}
<p>长度是否为5:{{ content_string | length_is:5 }}</p> {# 输出: 长度是否为5:True #}
<p>长度是否为6:{{ content_string | length_is:6 }}</p> {# 输出: 长度是否为6:False #}

Summary

Of Security CMSlengthThe filter is a powerful and thoughtful tool that calculates length in UTF-8 characters, providing precise and reliable length information for handling multi-language content, optimizing SEO fields, beautifying interfaces, and performing data validation.Combine other template tags and filters, you can easily build a more intelligent and robust website content display logic.

Frequently Asked Questions (FAQ)

  1. lengthDoes the filter calculate spaces and special characters in the string?Yes,lengthThe filter calculates each character in the string precisely, including spaces, punctuation, emojis, and various special symbols, each being counted as 1 unit of length.This is part of its UTF-8 character calculation feature.

  2. lengthFilters andtruncatecharsWhat are the differences between filters? lengthFilters are used forObtainstrings, arrays, or key-value pairstotal lengthHowevertruncatecharsFilter is used forcutA string to a specified length, and add an ellipsis at the end (if the original string exceeds the specified length). Simply put,lengthIt tells you how long it is,truncatecharsIs it to help you cut to how long.

  3. If I want to judge whether a variable is empty, I can uselengthfilter?OK. For strings, arrays, or key-value pairs, if they are empty,lengthThe filter will return 0. Therefore, you can use it to{% if my_variable | length > 0 %}to check if a variable has content, or use a more concise{% if my_variable %}(because the template engine treats empty strings, empty arrays, and so on as false values).

Related articles

How to extract HTML content (such as rich text fields) in AnQiCMS templates while maintaining the integrity of the tag structure?

In AnQiCMS templates, when handling content display, it is often necessary to truncate rich text fields (such as article details, product descriptions, etc.).Directly extracting strings from HTML content often leads to the destruction of tag structure, which can affect page layout and even cause rendering errors.幸运的是,AnQiCMS提供了一些非常实用的模板过滤器,可以帮助我们优雅地完成这项任务,同时确保HTML标签的完整性。

2025-11-07

How to truncate the article abstract to a fixed number of characters and automatically add an ellipsis at the end in AnQiCMS?

In website operations, how to effectively and beautifully display article lists or cards while avoiding excessive space occupied by long content is a common challenge.Especially on the homepage, category page, or search results page, we often need to extract part of the article content as a summary and elegantly add an ellipsis at the end to guide visitors to click and view the details.AnQiCMS fully considers the needs of content operators, making this operation very simple and intuitive through flexible template tags and powerful filters.How does AnQiCMS handle the article abstract content?

2025-11-07

How to uniformly manage the alignment format of text in AnQiCMS multi-site templates?

In AnQi CMS (AnQiCMS) multi-site environment, achieving unified management of text alignment formats across different sites is the key to enhancing brand consistency, optimizing user experience, and simplifying post-maintenance.Although each site may have independent templates and content, we can completely establish a set of efficient and unified alignment management strategies by cleverly utilizing the template mechanism and front-end technology of AnQiCMS.

2025-11-07

Does AnQiCMS filter support custom non-space characters for `ljust` or `rjust` padding?

In the practice of content operation on AnQiCMS, we often need to do refined layout and design of text content on the page.For example, to maintain the alignment of tables or list items, we may use string padding functions, such as left-aligned padding (`ljust`) or right-aligned padding (`rjust`).A common question is, does AnQiCMS's template filter support using non-space characters to fill in the `ljust` or `rjust` operations?Today, let's delve deeply into this issue

2025-11-07

In AnQiCMS template, how to truncate article titles by word and display an ellipsis to adapt to different layouts?

In modern web design, the flexibility of content display is crucial, especially for core elements like article titles.When the article title is too long and our layout space is limited, how to elegantly truncate the title and add an ellipsis so that it maintains readability and adapts to different devices and layouts is a problem often encountered in the development of AnQiCMS templates.Luckyly, AnQiCMS's powerful template engine provides a simple and efficient solution.

2025-11-07

How to batch remove all HTML tags from product descriptions in AnQiCMS and retain only plain text content?

In website operation, we often encounter the situation that product descriptions contain a large number of HTML tags.These tags may come from different content sources or may be accidentally introduced during the editing process, leading to poor display of the description in some scenarios, such as plain text email notifications, SEO summaries, or concise views on mobile devices.AnQi CMS provides a flexible way to solve this problem, whether it is to dynamically display plain text on the front end through templates or to perform batch processing on the back end, completely removing redundant HTML tags.

2025-11-07

How to remove only specific types of HTML tags in the AnQiCMS template (such as `<i>` or `<strong>`)?

In the template development of Anqi CMS, we often encounter the need to handle content output by rich text editors.This content usually includes various HTML tags, such as those used for emphasizing `<strong>`, for italicizing `<i>`, or others like `<em>`, `<span>`, `<div>` etc.

2025-11-07

How to automatically capitalize the first letter of the English name submitted by the user in the AnQiCMS template?

In website operation, we often encounter the need to display user submitted information, such as name.In order for this information to look more professional and unified, it is usually desired that the first letter of the English name be automatically capitalized.This not only enhances the beauty of the user interface, but also ensures the consistency of data display.In the flexible template system of AnQiCMS, implementing this requirement is very simple.

2025-11-07