How to use the `length` filter to get the length of a string, array, or key-value pair for display or judgment

Calendar 👁️ 79

In website content operation, we often encounter scenarios where we need to obtain or judge the length of data.For example, display the number of words in an article, the number of items in a list, or decide whether to display an element based on the content length.The template engine of AnQiCMS (AnQiCMS) provides a series of practical filters to help us meet these needs, among whichlengthandlength_isThe filter is among the best. It helps us easily implement these features, making the dynamic display and interaction logic of the website more flexible.

lengthFilter: Core tool for getting data length

As the name implies,lengthThe filter is used to obtain the "length" of a data item.It is very flexible, whether it is a string, an array (often referred to as the Go language's slice type in Anqicms templates), or a key-value pair (map), it can accurately give the number of elements or characters contained in it.

Specifically, whenlengthThe filter applies to a string and it calculates the actual Unicode character count of the string. This means that both a Chinese character and an English character are counted as1The length, not the original byte count. This is particularly friendly for operators of Chinese websites, as it conforms to our intuitive understanding of 'word count'.

When it is applied to an array (such as a list of articles, a collection of images) or a key-value pair (such as a custom parameter collection),lengththe filter will directly return the number of elements or key-value pairs it contains.

Usage example:

Assuming we have an article objectarchiveof whichTitleIs a string,Imagesis an image array, whereasParamsis a set of key-value pairs:

  • To get the length of a string:If you want to know the length of the article title, you can use it directly like this:

    <p>文章标题长度:{{ archive.Title | length }}</p>
    

    Ifarchive.TitleThe value is"安企CMS让内容管理更简单"the output will be12.

  • Get the length of the array:To display the number of images in an article, you can do it like this:

    <p>文章配图数量:{{ archive.Images | length }}</p>
    

    Ifarchive.ImagesIf it contains 3 images, the output will be:3.

  • Get the length of the key-value pair (Map):If you want to know how many custom parameters an article has, you can do it like this:

    <p>自定义参数数量:{{ archive.Params | length }}</p>
    

    Ifarchive.ParamsIf 5 custom parameters are defined, the output will be:5.

length_isFilter: a powerful tool for length judgment

In addition to simply getting the length, sometimes we need to make judgments based on the length, such as whether the length of a string is exactly equal to some value, or whether a list is exactly empty. At this time,length_isThe filter comes into play. It receives an expected length value as a parameter, compares it with the actual length, and returnsTrueorFalse(a boolean value).

This filter is very useful when it is necessary to control the page display logic according to the length of the data.For example, when the list is empty, display a prompt such as 'No data available', or display supplementary information when a certain description field is too short.

Usage example:

  • Check if the length of the string is equal to the specified value:If you need to check if the user's input nickname is exactly 6 characters:

    {% set username = "张三丰" %}
    {% if username | length_is: 6 %}
        <p>昵称长度符合要求。</p>
    {% else %}
        <p>昵称长度不符合要求。</p>
    {% endif %}
    

    Because the length of “张三丰” is 3, the output will be:昵称长度不符合要求。.

  • Check if the list is empty:Before displaying the comment list, we usually check if there are any comments.

    {% if comments | length_is: 0 %}
        <p>暂时还没有评论,快来发表您的看法吧!</p>
    {% else %}
        {# 显示评论列表的代码 #}
    {% endif %}
    

    So whencommentsIf the array is empty, a friendly reminder will be displayed on the page.

Application scenario: Make data management smarter

tolengthandlength_isFilter integrated into template design, bringing many conveniences and optimizations:

  1. Dynamic display of count:Display the number of articles under each category on the category page, or the number of products under each brand in the product list. For example:{{ category.Title }} ({{ category.Archives | length }} 篇).
  2. Content truncation and prompt:For an article abstract or description, you can uselengthDetermine its length, if it exceeds the preset value, then combineslicethe filter to truncate and add an ellipsis to keep the page tidy.
  3. Conditional element display:When a certain image collection is empty, the image gallery may not be displayed;When a contact information field is empty, the corresponding contact icon may not be displayed.This avoids the visual confusion caused by displaying empty data.
  4. Form validation prompt:Perform real-time validation of the length of the user input field on the front end, and provide prompts to enhance the user experience.

By flexible applicationlengthandlength_isThe filter allows us to easily obtain and judge the length of data in the Anqi CMS template, thereby building a more dynamic and user-friendly website interface, making content operations twice as effective.


Frequently Asked Questions (FAQ)

1.lengthThe filter can handle what data types? What will be returned if the object is not a string or an array?

lengthThe filter is mainly designed to handle strings, Go language slices (corresponding to arrays or lists in templates), and maps (corresponding to key-value pairs).It calculates the number of Unicode characters in a string;For slice and map, it calculates the number of elements or key-value pairs it contains.If for non-above types (such as pure numbers{{ 123 | length }}and a boolean value{{ true | length }})lengthThe filter usually returns0But it is recommended to avoid using unexpected types as much as possible to ensure clarity in logic.

2.lengthWhen calculating the length of Chinese or multi-byte characters, is the filter calculated by bytes or by characters?

Of Security CMSlengthThe filter processes strings byUnicode character countIt is calculated. This means that a Chinese character (such as “你”) and an English character (such as “a”) are both counted as1length, this conforms to our usual habit of counting 'word count', rather than the original byte length.

**3. In addition to checking if it is equal to0,length_iswhat other length checks can it be used for

Related articles

How to use the `contain` filter in AnQiCMS template to determine whether a string or an array contains a specific keyword?

During the process of building a website on AnQiCMS, flexibly displaying information according to the characteristics of the content is the key to improving user experience and operational efficiency.To achieve this, the system has built-in many practical template filters, among which the `contain` filter is a powerful tool for determining whether the content contains specific keywords.It can help you match content directly at the template level without modifying the backend code, thereby making your website content display more intelligent and personalized.

2025-11-07

How to retrieve and display a list of documents under a specified Tag, and support pagination?

In website content management, categorizing and displaying documents according to their tags (Tags) is an important strategy to enhance user experience and content discoverability.AnQiCMS provides a set of intuitive and powerful template tags that help us easily achieve this goal, while also supporting flexible pagination functionality, even when faced with massive amounts of content, it can maintain the page's cleanliness and loading speed.

2025-11-07

How to display a multi-level nested category list in AnQiCMS, such as top-level categories and their subcategories?

When building a website, a clear and organized content structure is the foundation for improving user experience and search engine optimization.Especially for content-rich websites, how to efficiently display multi-level nested category lists, such as top-level categories and their subcategories, is a concern for many operators.AnQiCMS is a flexible enterprise-level content management system that provides intuitive and powerful template tags, allowing you to easily meet this requirement.

2025-11-07

How to get and display the detailed information of the current category in AnQiCMS template, such as title, description, thumbnail, and Banner group image?

Building a website in AnQiCMS, especially when we need to present rich and accurate information on category pages, it is particularly important to deeply understand how to obtain detailed data of the current category in templates.This is not just for aesthetics, but also to provide a better user experience and search engine optimization.The AnQiCMS template system is designed to be very flexible and easy to use, it uses syntax similar to the Django template engine.

2025-11-07

How to display a custom SEO title on the article detail page instead of the article title?

In content operation, setting the title of the website article detail page is a key link.We often encounter such situations: the content title of the article itself needs to be eye-catching and creative, in order to attract readers' clicks;And the page title required for search engine optimization (SEO) (i.e., the content of the `<title>` tag displayed on the browser tab), is more focused on keyword layout, length control, and search engine friendliness.In AnQiCMS, you can fully flexibly manage these two different titles to ensure both user experience and SEO effectiveness.

2025-11-07

How to configure URL rewrite rules in Anqi CMS to optimize search engine crawling?

In website operation, Search Engine Optimization (SEO) plays a crucial role, and a friendly URL structure is a key factor in improving the performance of a website in search engines.A clear and meaningful URL not only helps search engines better understand the content of the page, but also allows visitors to see the theme of the page at a glance, enhancing the user experience.Traditional dynamic URLs often contain parameters that are difficult to understand, which is not friendly to SEO and users.Fortunately, AnQi CMS provides a powerful static rule configuration function, allowing you to easily optimize the URL structure of your website.

2025-11-07

How to display the multi-language content switch button on the website front end?

On AnQiCMS, it is crucial to display a multilingual content switch button on the website front-end to expand the global user base and enhance the user experience.AnQiCMS with its powerful multilingual support and flexible template mechanism makes implementing this feature intuitive and efficient. ### AnQiCMS multilingual mechanism overview AnQiCMS considered the needs of global content publishing from the outset.Its multilingual support is centered around the "multi-site management" feature.This means that you can create different sites to represent different language versions. For example

2025-11-07

Where is the TDK (Title, Keywords, Description) information of the home page set and displayed?

The TDK (Title, Keywords, Description) information on the homepage is crucial for the performance of the website in search engines.It is not only the key for search engines to understand the core content of a website, but also an important basis for users to decide whether to click on a website in the search results page.AnQi CMS is an efficient content management system that provides an intuitive and convenient TDK management function, allowing us to easily optimize the visibility of the website homepage in search engines.

2025-11-07