How to get the length of a string, array, or object?

Calendar 👁️ 84

When managing website content in AnQi CMS, we often need to flexibly adjust the page display based on the number of elements in a string, array, or collection.Whether it is to judge whether the length of the article title needs to be truncated, or to count how many documents are under a certain category, or to display the number of user comments, obtaining the 'length' of this content is the key to dynamic display and logical judgment.

The AnQi CMS template engine provides built-in features that are simple and efficient, helping us easily deal with these scenarios. Among them,lengthThe filter is a powerful assistant to get the length of strings, arrays, or key-value pairs, andlength_isThe filter also allows you to conveniently make length conditional judgments.

Master it easilylengthFilter

lengthThe filter, as the name implies, is used to obtain the length of a specified data type. It is very intelligent and can return different length information based on the type of variable you pass in:

  • For strings:It calculates the number of actual characters in a string. Even Chinese characters are counted as a single character, not by byte count.
  • For an array (Slice) or list:It returns the total number of elements contained in the array or list.
  • For a key-value pair (Map) or object:It will return the number of entries in the key-value pair, that is, how many properties there are.

UselengthThe filter is very intuitive, you just need to pass the variable you want to calculate the length through the pipeline symbol|Connected tolengthThat's it, for example:{{ 您的变量|length }}.

Let's look at some actual examples:

Get the length of a string

Suppose you have a piece of text, whether it's English or Chinese, and you want to know its character length:

{# 假设有一个字符串变量 title = "欢迎使用安企CMS" #}
<p>文章标题的字符长度是:{{ title|length }}</p>

{# 假设有一个字符串变量 description = "AnQiCMS is a powerful CMS." #}
<p>描述内容的字符长度是:{{ description|length }}</p>

This code will output separately:10and26This indicates:lengthThe filter can accurately calculate the length of a string containing both Chinese and English characters.

Get the length of an array or list

When processing a list of articles, images, or tags,lengthThe filter can help you quickly understand the amount of data. For example, you may want to know how many documents are on the current page, or how many associated items are under a certain tag:

{% archiveList articles with type="list" limit="5" %}
    <p>当前页面有 {{ articles|length }} 篇文档。</p>
    {# 接着您可以在这里遍历 articles 列表,展示每篇文档的信息 #}
    {% for item in articles %}
        {# ... 展示文档内容 ... #}
    {% endfor %}
{% endarchiveList %}

{% tagList tags with limit="10" %}
    <p>当前文章关联了 {{ tags|length }} 个标签。</p>
    {% for item in tags %}
        {# ... 展示标签信息 ... #}
    {% endfor %}
{% endtagList %}

IfarticlesThe list actually returned 5 documents, so the first{{ articles|length }}it will be displayed5Similarly, iftagsThe list returns 3 tags, it will display3This is very useful for controlling loop iterations, displaying total summary, and other scenarios.

Get the number of key-value pairs or object properties.

In the AnQi CMS template, some configurations or custom fields may exist in the form of key-value pairs.lengthThe filter can also calculate the number of entries for these key-value pairs. For example, if you have customized a set of document parametersparamsand want to know how many parameters there are:

{% archiveParams params %}
    <p>当前文档设置了 {{ params|length }} 个自定义参数。</p>
    {% for item in params %}
        <p>{{ item.Name }}:{{ item.Value }}</p>
    {% endfor %}
{% endarchiveParams %}

Hereparams|lengthwill returnparamsThe number of parameters contained in the set, helping you dynamically display the completeness of custom information.

Combinelength_isMake a conditional judgment.

Sometimes we need to make a judgment based on the length directly, such as 'If the number of articles is zero, display 'No content'.' At this time,length_isThe filter comes into play.

length_isA filter used to determine if the length of a variable is equal to a specified value, it will returnTrueorFalse(a boolean value).

The method of use is{{ 您的变量|length_is:数字 }}, which is usually配合ifused with logical judgment tags:

{% archiveList articles with type="list" limit="0" %} {# 这里故意设置 limit 为 0,模拟列表为空 #}
    {% if articles|length_is:0 %}
        <p>抱歉,当前分类暂无文章内容。</p>
    {% else %}
        <p>发现 {{ articles|length }} 篇文章,快来阅读吧!</p>
        {% for item in articles %}
            {# ... 展示文档内容 ... #}
        {% endfor %}
    {% endif %}
{% endarchiveList %}

In this example, ifarticlesThe list length is 0, the page will display If not, the number of articles will be displayed along with the list of articles. This allows the template to adjust the display content in real-time based on the data, enhancing the user experience.

Masterlengthandlength_isThe filter can make your safe CMS template development and content operation more flexible and efficient, whether it is refined layout or optimized user interaction, they will be indispensable tools for you.


Frequently Asked Questions (FAQ)

1.lengthandlength_isWhat are the main differences between these two filters? lengthFilters are used toObtainThe actual length of a string, array, or key-value pair, it will return a specific number. Andlength_isThe filter is used tothe judgment.Whether the length of a variable is equal to the number you specified, it will return a boolean value (TrueorFalse) and is usually used in{% if %}such conditional statements.

2.lengthIs the filter calculating the length of a string by bytes or characters?In the AnQi CMS template engine,lengthThe filter calculates the length of a string byactual character countIt is counted as characters, not by bytes. This means that whether it is English letters, numbers, or Chinese characters, each one is counted as a character. For example,{{ "你好世界"|length }}The result is4.

3. If I want to know if a list (array) is empty, otherlength_is:0There are other more concise methods?Of course! The template engine of AnQi CMS provides{% for ... empty ... endfor %}This is a very elegant structure to handle the case of an empty list. Whenforthe list being traversed by a loop is empty,{% empty %}and{% endfor %}the content between the brackets will be displayed and the normal loop body will not be executed. For example:

{% archiveList myArticles %}
    {% for article in myArticles %}
        <p>{{ article.Title }}</p>
    {% empty %}
        <p>暂无相关文章。</p>
    {% endfor %}
{% endarchiveList %}

This method is very excellent in terms of code readability and conciseness.

Related articles

How to display a default value when a variable is empty?

In website operation, we often encounter such situations: a content field may not be filled in for various reasons, such as the author of the article, image description, or specific parameters of a product.If the template outputs a blank directly when displaying this content, it not only affects the aesthetics but may also confuse the user.At this time, how to display a friendly default value when a variable is empty has become a very practical skill.The AnQi CMS template system, with its flexible and powerful features, provides us with various methods to elegantly solve this problem

2025-11-09

How to convert a string to uppercase, lowercase, or title case?

In website content operation, the way content is presented often determines the overall impression of users on the website.Whether it is to maintain brand style consistency or to improve the readability of text, flexible case conversion of strings is a basic and important operation.AnQiCMS (AnQiCMS) understands this, and it has built-in simple and easy-to-use filters (Filters) in its powerful template engine, allowing you to easily perform string transformations such as uppercase, lowercase, and capitalization without complex programming.We will introduce in detail how to use the Anqi CMS template

2025-11-09

How to perform basic arithmetic operations in the template?

In Anqi CMS template design, it can flexibly handle data, perform simple calculations, and is an indispensable part of creating dynamic and functional websites.You may find that in addition to displaying the content itself, it is also necessary to perform some basic arithmetic operations at the template level, such as calculating the total price of goods, displaying the discounted price, or dynamically adjusting the style of elements based on numerical values.The AnQi CMS template engine (similar to Django syntax) provides us with intuitive and powerful arithmetic calculation capabilities, allowing these requirements to be easily implemented in the template.###

2025-11-09

How to automatically convert URL strings in text to clickable links?

In daily content operations, we often need to mention various URLs in articles, product descriptions, or page introductions.If these URLs are displayed as plain text, users will need to manually copy and paste them to access, which undoubtedly will greatly reduce their reading experience and the interactivity of our website.How can we automatically make the URL strings in these texts clickable?In AnQi CMS, this implementation is very simple, no complex code development is required, just use its powerful template filter function to easily handle it.

2025-11-09

How to format a floating-point number to a specified number of decimal places?

How to accurately control the decimal places of floating-point numbers in AnQiCMS?In website content operations, we often encounter situations where we need to display prices, statistical data, measurement results, and other floating-point numbers.However, the original floating-point numbers often have unnecessary decimal places, which not only affects the appearance but may also reduce the readability of the data.AnQiCMS fully considers this user's needs, providing flexible and powerful template filters to help us easily implement the formatting of floating-point numbers, making data display more professional and accurate.### Use `floatformat`

2025-11-09

How to center or align a string to a specified length?

When building website content, we often need to fine-tune the text layout to ensure that the information presented is both beautiful and clear.Whether it is a list, table, product parameters, or other structured display data, maintaining visual alignment and consistency is crucial for improving user experience.Aq CMS, known for its high flexibility and ease of use as a content management system, deeply understands the importance of content presentation and has built a series of powerful template filters to help us easily align and center strings

2025-11-09

How to determine if a string or array contains a specific keyword?

In AnQi CMS, efficiently identify key information in content: string and array keyword judgment techniques As a content operator, we often need to handle a large amount of text data, from article titles, content descriptions to custom fields, rich and diverse information.In order to optimize search engine (SEO), implement content intelligent recommendation, or perform simple data validation, quickly judge whether a string or array contains a specific keyword is a very practical and efficient skill.In the flexible and powerful template system of Anqi CMS, this task becomes effortless.Utilize built-in filters

2025-11-09

How to calculate the number of times a specific keyword appears in a string or array?

In AnQiCMS content management practice, we often need to carry out refined analysis and optimization of website content.In which, calculating the number of times a specific keyword appears in an article, title, or dataset is a basic and important requirement.In order to evaluate SEO keyword density, analyze content quality, or conduct data statistics, AnQiCMS provides convenient and efficient solutions.This article will deeply explore how to utilize the built-in features of AnQiCMS to easily achieve this goal.### Core Tool: `count`

2025-11-09