How to use the `length` filter to get the length of a string, array, or key-value pair in AnQiCMS templates?

Calendar 👁️ 75

In AnQiCMS template development, we often need to process and judge the data displayed on the page.Among these, getting the length of a string, array, or key-value pair is a very basic and practical operation.lengthThe filter makes this task simple and intuitive.

Get to knowlengthFilter: A tool to get the length of data

lengthThe filter, as the name implies, is a tool used to obtain the "length" of data. Whether you want to know how many characters a piece of text has, how many items a list contains, or how many key-value pairs a set of configuration options has,lengthThe filter can help you easily achieve this. Its design philosophy is to simplify complexity, allowing template developers to complete a quick perception of the scale of data with the least amount of code.

Its basic usage is very concise, just need to use the pipeline symbol after the variable to get the length|Continuelengthand it is done:{{ obj|length }}.

lengthFilter application on different data types

lengthThe filter can intelligently identify the data type of the incoming data and return the corresponding length information.

1. Get the length of a string.

When faced with a piece of text, sometimes you need to know how many characters it has.lengthThe filter calculates the actual number of UTF-8 characters in the string. This means that whether it is English letters, numbers, or Chinese characters, each character is counted as 1.

For example, if you have a variable namedtitlewith the value “AnQi CMS makes your website more secure”, to get its character length, you can use the following:

{% set title = "安企CMS让你的网站更安全" %}
<p>标题的字符长度是:{{ title|length }}</p>

This code will execute and then, the page will display: 'The character length of the title is: 13'.Similarly, if it is an English title, such as 'AnQiCMS is Great', its length will also be returned according to the actual number of characters.

2. Get the length of the array (Slice)

In the AnQiCMS template, we often get fromarchiveList/categoryListRetrieve a series of data from tags, which is usually in the form of an array (or a Slice in Go language). To get the number of elements in this array,lengthThe filter applies equally.

Assuming you pass througharchiveListLabel to get a group of article data and name itarchives:

{% archiveList archives with type="list" limit="10" %}
    <p>当前页面共有 {{ archives|length }} 篇文章。</p>
    <ul>
        {% for item in archives %}
            <li>{{ item.Title }}</li>
        {% endfor %}
    </ul>
{% endarchiveList %}

IfarchivesThere are actually 5 articles, then the page will display: "There are a total of 5 articles on the current page."

3. Get the length of the key-value pair (Map or Struct)

When data exists in the form of key-value pairs, such as througharchiveParamsThe tag retrieves the document custom parameters, or other custom structures (Struct) or maps (Map) objects,lengthThe filter calculates the number of key-value pairs in it.

For example, if you get a document's custom parameterparams:

{% archiveParams params %}
    <p>该文档共有 {{ params|length }} 个自定义参数。</p>
    <ul>
        {% for item in params %}
            <li>{{ item.Name }}:{{ item.Value }}</li>
        {% endfor %}
    </ul>
{% endarchiveParams %}

If the document is set to 3 custom parameters (such as "author", "source", "publish date"), then the page will display: "The document has 3 custom parameters."

Advanced usage:length_isFilter

In addition to simply getting the length, AnQiCMS also provides a related filterlength_isUsed to determine whether the length of a variable is equal to a specified value. This is very useful when making conditional judgments.

length_isThe filter takes a parameter, which is the length value you want to compare. It returns a boolean value (TrueorFalse)

For example, to determine whether a variableitemshas a length of 5:

{% set items = "这是一个测试字符串" %}
{% if items|length_is:8 %}
    <p>字符串“{{ items }}”的长度正好是 8。</p>
{% else %}
    <p>字符串“{{ items }}”的长度不是 8。</p>
{% endif %}

length_isThe filter applies not only to strings, but also to arrays and key-value pairs, with the same judgment logic aslengththe filter is consistent.

Summary

lengthThe filter is a very basic but powerful tool in the AnQiCMS template, making it easy to obtain the length of strings, arrays, or key-value pairs. Combinedlength_isFilter, we can make more refined data display and logical control in the template, thereby building more flexible and more responsive website content.Master these filters, and it will greatly enhance your content operation efficiency and template development experience on the AnQiCMS platform.


Frequently Asked Questions (FAQ)

  1. lengthWhat data types can the filter calculate the length of? lengthThe filter is mainly used to calculate the number of characters in a string, the number of elements in an array (Slice), and the number of key-value pairs in a map (or struct).For other types of data, such as pure numbers, it may return unexpected results or even report an error.

  2. lengthWhat is the counting method for Chinese characters in the filter? lengthThe filter counts Chinese characters and English characters in the same way, both are counted according to the actual UTF-8 character count.That is to say, a Chinese character (such as “安”) is counted as 1, consistent with the count of an English letter (such as “A”), not the number of bytes.

  3. exceptlengthWhat are some filters that can be used to determine or process the length of a string or collection?exceptlengthandlength_is,AnQiCMS also provides some other filters related to string or collection length processing. For example,truncatecharsandtruncatewordsyou can truncate strings or HTML content and add an ellipsis;wordcountYou can count the number of words in a string (separated by spaces);sliceThe filter can extract the specified part of a string or array. These filters collectively provide rich choices for the flexible display of template content.

Related articles

How do the `urlize` and `urlizetrunc` filters handle URL links in the AnQiCMS template?

In website operation, we often need to embed various links in the content, whether they point to internal resources or external references.Manually converting plain text links into clickable hyperlinks is not only inefficient but also prone to errors.It is more important that standardized link handling is crucial for search engine optimization (SEO) and user experience.

2025-11-08

How to format timestamp output to date or time string in AnQiCMS template?

In website operation, the date and time information of content publication, update, and other aspects are crucial for user experience and content management.AnQiCMS as a rich-featured content management system, provides flexible template tags, allowing users to easily format the timestamp data stored in the background into various easily readable date or time strings to meet different display requirements.

2025-11-08

How to flexibly control the display quantity and style of pagination page numbers with the `pagination` tag of AnQiCMS?

When managing a content-rich website, an efficient page navigation system is crucial for enhancing user experience and search engine optimization (SEO).AnQi CMS knows this, its built-in `pagination` tag provides us with detailed control, making the website page number display both flexible and beautiful.This article will guide you to understand how to use the `pagination` tag, flexibly control the display quantity and style of pagination page numbers.

2025-11-08

How to automatically generate the breadcrumb navigation of the page in the AnQiCMS template using the `breadcrumb` tag?

When browsing websites, we often notice a path information string at the top or bottom of the page, which clearly indicates our current location, such as "Home > Category > Article Title."}This is what we commonly refer to as Breadcrumb Navigation.It not only helps users better understand the website structure and improve the browsing experience, but also has a significant value for search engine optimization (SEO).Why is breadcrumb navigation important? For users, breadcrumb navigation is like a mini-map.

2025-11-08

What search engines does the "Link Push" feature of AnQiCMS backend support for active push?

Today, with the rapid growth of internet content, the quick inclusion of website content is an important factor in increasing website traffic and influence.For many content operators and enterprises, how to make search engines discover and index new content on their websites in a timely manner is a core issue in SEO work.AnQiCMS (AnQi CMS) deeply understands this need, especially in the backend, integrating a convenient and powerful "link push" function, aimed at helping users deliver their carefully crafted content to major search engines in the shortest possible time, effectively shortening the cycle from content publication to indexing.###

2025-11-08

How does AnQiCMS's `filter` tag combine multiple filters to process content in a chain?

AnQiCMS provides flexible and powerful content management capabilities, among which the template engine is the core of our daily operations and content display.When processing website content, we often encounter situations where we need to perform multi-step transformations to achieve the final display effect.For example, a long article summary may need to be truncated first, then ensure all letters are lowercase, and finally calculate the length of the processed text.If each time is handled manually through complex code logic, it is not only inefficient but also makes the template difficult to maintain.

2025-11-08

How to customize the front-end content display layout of Anqi CMS website?

AnQiCMS provides highly flexible frontend content display layout customization capabilities, allowing websites to present unique visual effects and information structures according to specific needs.This is not only about the appearance of the website, but also about how to deliver content efficiently and accurately to visitors.By understanding the template mechanism and various functions of AnQiCMS, users can easily achieve fine-grained control from the overall theme style to the display of single content.

2025-11-08

How can AnQi CMS be configured and display multilingual content to expand the international market?

Expand the international market, allowing your content to reach global users is an important part of many enterprises' digital strategies.AnQiCMS (AnQiCMS) is well aware of this need and therefore built-in strong multilingual support and multi-site management capabilities from the very beginning, helping users efficiently configure and display multilingual content. ### Embarking on the journey of internationalization: The cornerstone of multilingual support AnQi CMS is committed to providing small and medium-sized enterprises and content operation teams with an efficient and flexible content management platform.

2025-11-08