How to get the actual length of a string or array in AnQiCMS template (number of characters or elements)?

Calendar 👁️ 61

When managing website content in Anqi CMS, you often encounter situations where you need to get the number of characters in a text or determine how many elements are contained in a list or array.In order to control the page layout, ensure the display length of the title introduction, or dynamically adjust the display logic based on the amount of data, it is crucial to understand how to obtain these 'length' information in the template for creating flexible and user-friendly websites.

The Anqi CMS template engine provides a simple and powerful way to handle such requirements, with the most core being thatlengthThe filter that helps us easily get the number of characters in a string, as well as the number of elements in an array or a key-value pair (map).

UselengthFilter to get length

lengthThe filter is the main force for dealing with such "length" issues. Its usage is very intuitive, just pass the variable to be measured through the pipe symbol|pass tolengthJust do it.

For example, if you want to get the character count of a string, you can use it like this:

{{ "欢迎使用安企CMS"|length }}

For Chinese and English,lengthThe filters will correctly calculate their character count. For example, the above code will output8It accurately calculates each Chinese character in the string. If it is an English string, such as"hello world"it will output:11.

When dealing with arrays or lists,lengthThe filter applies as well, it returns the total number of elements in the array. For example, you can fromarchiveLista list of articles labeledarchives:

{% archiveList archives with type="list" limit="10" %}
    {# ... 循环文章列表 ... #}
{% endarchiveList %}

<p>目前有 {{ archives|length }} 篇文章。</p>

This will display.archivesThe actual number of articles contained in the array. For key-value pairs (map) or objects,lengthThe filter will return the number of key-value pairs.

CombineifThe statement performs conditional judgment

After getting the length, we often need to make some conditional judgments based on this number to control the display of content. At this time,lengththe filter meetsifUsing logical judgment tags in combination can exert a powerful effect.

For example, you may want to display a prompt message when the article list is empty instead of a blank area:

{% archiveList archives with type="list" limit="10" %}
    {% if archives|length > 0 %}
        <ul>
            {% for item in archives %}
                <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
            {% endfor %}
        </ul>
    {% else %}
        <p>当前分类下暂无文章。</p>
    {% endif %}
{% endarchiveList %}

Or, would you like to limit the display length of a description text, truncating it if it exceeds a certain number of characters:

{% set description_length = item.Description|length %}
{% if description_length > 50 %}
    <p>{{ item.Description|truncatechars:50 }}</p>
{% else %}
    <p>{{ item.Description }}</p>
{% endif %}

Here we also introducedtruncatecharsA filter that can truncate a string to a specified number of characters and automatically add an ellipsis, which is a good partner in practical applications.lengthA filter is a good partner.

length_isFilter: directly judge whether the length matches.

exceptlengthThe filter directly gets the length, and the Anqi CMS also provides alength_isA filter used to determine if the length of a variable is exactly equal to a specific number. This can make the code more concise in some scenarios.

The usage is as follows:

{% if "你好世界"|length_is:4 %}
    <p>字符串“你好世界”的长度确实是4个字符。</p>
{% else %}
    <p>字符串长度不匹配。</p>
{% endif %}

length_isIt will return directlyTrueorFalseto make it convenient for you inifUse directly in the statement.

Summary

In the AnQi CMS template, to obtain the actual length of a string or an array, mainly rely onlengthfilter. It can accurately calculate the number of characters or the number of elements, and can be used withifTags can be flexibly combined to implement various conditional judgments and dynamic content display.length_isThe filter provides a convenient way to determine if the length is equal to the expected value. Mastering these tools will allow you to better control the presentation of website content and enhance user experience.


Frequently Asked Questions (FAQ)

Q1:lengthDoes the filter count a Chinese character as one character when calculating the length of a Chinese string?A1: Yes, it is in AnQi CMS.lengthThe filter calculates the length of a string based on the actual character count in UTF-8 encoding.This means that whether it is English, numbers, or Chinese characters, each character is counted as a unit.

Q2: If I need to limit the number of characters displayed in the article title and show an ellipsis for the part that exceeds, what should I do?A2: In this case, you can combine the use oflengthThe filter makes a judgment and usestruncatecharsThe filter is used to truncate strings. For example:{% if item.Title|length > 30 %}{{ item.Title|truncatechars:30 }}{% else %}{{ item.Title }}{% endif %}.truncatecharsThe filter automatically adds at the truncation point....

Q3: I have a list of images and want to check if it is empty to decide whether to display the image area. How should I operate?A3: You can uselengthA filter to check the number of elements in a list. For example, if your image list variable is nameditem.Images, you can judge like this:{% if item.Images|length > 0 %} <div class="image-gallery"> ...显示图片... </div> {% endif %}. The image area will only display when the image list is not empty.

Related articles

The `make_list` filter and the `split` filter are applicable to which scenarios in converting strings to character arrays in AnQiCMS templates?

In AnQiCMS template development, we often need to process string type data, where converting a string to an array is a common requirement.AnQiCMS powerful template engine provides a variety of filters to assist in completing such tasks, among which the `make_list` and `split` filters are the tools for converting strings to arrays.Although they can both 'turn' strings into arrays, there are essential differences in their application scenarios and conversion logic.Understanding these differences can help us achieve template functionality more efficiently and accurately.##

2025-11-08

How to split a string containing multiple keywords in AnQiCMS template by spaces, commas, or a custom delimiter into an array?

In AnQiCMS (AnQiCMS) content management and template development, we often encounter scenarios where we need to process strings containing multiple keywords.For example, an article may have a comma-separated list of keywords, or product attributes are space-separated tags.Make full use of these data and display them flexibly in the template, you need to split these strings into traversable arrays precisely.AnQiCMS uses a template engine syntax similar to Django, providing powerful filter functions to handle such needs.Among, `split`

2025-11-08

In AnQiCMS template language, what are the similarities and differences between the `join` filter and other string concatenation methods, and what are their applicable scenarios?

In Anqi CMS template language, combining multiple strings or data fragments into a complete string is a very common requirement in front-end display.There are many ways to achieve this goal, each method has its unique application scenarios and advantages.Today, let's delve into the differences and similarities between the `join` filter and other commonly used string concatenation methods.### `join` filter: A bridge from array to string The `join` filter plays a very clear and efficient role in AnQiCMS template language

2025-11-08

How to customize fields in the AnQiCMS backend where a field stores multiple choices (an array), and clearly display them on the frontend page using the `join` filter?

The AnQi CMS provides great convenience for website operators with its flexible content model and powerful custom features.In daily content management, we often encounter situations where we need to add multiple selection properties to articles or products, such as a product may have multiple colors, different sizes, etc.How to display them in a clear and beautiful way on the front-end page when this information is stored in the background through custom fields in the form of multi-select values has become the problem we need to solve.### Understanding the Multi-Select Custom Fields in AnQi CMS On the AnQi CMS backend

2025-11-08

How to determine if the length of a variable in the AnQiCMS template matches the expected value and make a judgment in the conditional statement?

In website content management, flexibly controlling the way content is displayed is crucial for improving user experience and page aesthetics.AnQiCMS (AnQiCMS) provides a powerful template engine, allowing us to easily determine how to display page elements based on the characteristics of the content, such as the length of a variable.When you need to judge whether the length of a variable meets the expected requirements and perform different operations in the template based on this, the template tags and filters of Anqi CMS provide an intuitive and efficient solution.Flexible control of content display: The importance of length judgment Imagine one

2025-11-08

How to calculate the total number of times a specific keyword appears in a line string or an array in the AnQiCMS template?

In AnQiCMS (AnQiCMS) template development, we often need to flexibly handle various content on the page.For example, you may need to analyze the frequency of a specific word in an article, or check how many times an element is mentioned in a list.The AnQi CMS powerful template engine provides a variety of practical filters (Filter) that can help you easily meet these needs.The function used to calculate the total number of times a specific keyword or element appears is exactly the focus of our discussion today.### Core Function: `count`

2025-11-08

How to batch remove leading, trailing spaces or specific characters from AnQiCMS template strings for data cleaning and formatting?

When using AnQiCMS for website content management, we often encounter situations where we need to fine-tune the text output in templates.Whether it is data obtained from a database or content entered in an editor, it may contain extraneous spaces, line breaks, or even specific characters that are not intended to be displayed.In order to ensure the tidiness, consistency of website content, and to enhance user experience and search engine friendliness, it is particularly important to clean and format the data.AnQiCMS provides a flexible and powerful template engine, its syntax is similar to Django

2025-11-08

What are the common practical application scenarios for the `cut` filter when removing specified characters from any position in the AnQiCMS template string?

In AnQiCMS template design, in order to present the content effect that best meets expectations, we often need to process strings finely.Among the many built-in filters, the `cut` filter is a seemingly simple yet extremely practical tool.Its core function is to remove the specified characters from any position in the template string, which makes it have a unique application value in content cleaning, formatting, and enhancing the user reading experience.The `cut` filter works very directly: it traverses the target string and removes all segments that match the specified character

2025-11-08