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