How to get the accurate length of strings, arrays, or key-value pairs in AnQi CMS templates?

Calendar 👁️ 53

In website content management, we often need to finely control the displayed data, such as limiting the number of characters in article titles, checking if the image collection is empty, or counting how many items are in a list.As an experienced website operations expert, I know how AnQiCMS's powerful and flexible template engine can help us meet these needs.Today, let's delve into how to accurately obtain the length of strings, arrays, or key-value pairs in the AnQiCMS template, which is mainly due to its built-inlengthandlength_isfilter.

AnQiCMS template syntax absorbs the essence of Django template engine, while combining the efficient characteristics of Go language, providing rich and practical tags and filters for template creators. When faced with the common need of “getting length”,lengthThe filter is our powerful assistant.

The secret to accurately obtain the total amount of data:lengthFilter

lengthThe filter is like a diligent counter that can calculate the total length or total quantity of various data types.

Firstly, forstring typeof the data,lengthThe filter accurately calculates the number of characters contained.This is particularly noteworthy, as both English characters and complex UTF-8 encoded Chinese characters are recognized as independent character units.This means, when you need to limit the display word count of the article title, or format according to the length of the abstract,lengthThe filter provides a very intuitive and accurate basis.

For example, if you have a variabletitleContaining "Anqi CMS, Efficient Content Management", using{{ title|length }}it will return10It is not calculated by the number of bytes. Similarly, for the English string "AnQiCMS",{{ "AnQiCMS"|length }}it will also return7.

Secondly, when we need to know aArray (or a slice in Go language)how many elements it contains when,lengththe filter can also be useful. Suppose you are iterating through a list of imagesimagesTo find out how many images are in this list, just use{{ images|length }}You can easily get the total number of elements. For example, ifimagesVariables contain["pic1.jpg", "pic2.jpg", "pic3.jpg"]then{{ images|length }}The output is3.

Moreover, if your data iskey-value pair (map),lengthThe filter will return the total number of key-value pairs in the map. This undoubtedly provides great convenience for scenarios such as dynamic display of configuration items or user information. For example, a user configurationuser_settingsincluding{"theme": "dark", "language": "zh-cn"}then{{ user_settings|length }}It will return2.

Flexibly judge whether the length meets the standard:length_isFilter

In addition to obtaining the total length of the data, sometimes we are more concerned about whether the length of the data meets a specific requirement. At this time,length_isThe filter is particularly useful. It allows you to compare the actual length of the data with a preset value and return it directlyTrueorFalse(Boolean value). This direct judgment result is very suitable for use in conditional statements (for example{% if %}label) to control the display logic of content.

Continue with the above example: If you want to check if the length of the article title is exactly10characters, you can use{% if title|length_is:10 %}IftitleIs "AnQi CMS, an efficient content management system", then this condition judgment will beTrue. Similarly, you can check if the image list contains a specific number of images, for example{% if images|length_is:3 %}To determine if the list exactly has three images.

Application in practice and more considerations

In the actual operation of the website,lengthandlength_isFilters have a wide range of application scenarios:

  • Content truncation and prompt:You can decide whether to display the '...Read More' prompt or directly truncate the content based on the title length or description length on the article list page.
  • Image collection or attachment detection:Determine if the content is accompanied by an image or other attachments, for example{% if item.Images|length > 0 %}If an image exists, the image area will be displayed.
  • Form validation (auxiliary prompt):Provide real-time feedback based on the length of the input in the input box, such as "Insufficient characters entered, less than 10."
  • Dynamic display of navigation menu:Adjust the style or layout of the parent menu based on the number of submenus.

AlthoughlengthThe filter is used to get the total length, but in some specific scenarios, you may also need other filters related to 'quantity'. For example, AnQiCMS also providescountA filter to calculate the number of occurrences of a specific substring or element in a string or array whilewordcountThe filter can count the number of words in a string (usually separated by spaces). Understanding the differences between these filters can help you handle various content display logic more accurately.

In summary, within the AnQiCMS template,lengthandlength_isThe filter is a powerful assistant for you to control the content display logic.They are simple to use, powerful, and can help you build smarter, more interactive website interfaces, thereby greatly enhancing user experience and operational efficiency.


Frequently Asked Questions (FAQ)

Q1:lengthWhat data types can the filter calculate the length of? A1: lengthThe filter is mainly used to calculate the number of characters in a string (supports UTF-8 multibyte characters), as well as the total number of elements in an array (or a slice in Go language) and a key-value pair (map).

Q2:lengthandcountWhat are the differences between filters? A2: lengthThe filter is used to obtain the "total" length or "total" number of elements of the entire string, array, or key-value pair.countThe filter is to calculate the number of times a specific substring or element appears in a string or array. For example,"hello world"|lengthwill return11while"hello world"|count:"o"it will return2.

Q3: If I want to check if a variable (such as a string or array) is empty, besideslengthfilters, are there any more concise methods? A3:Yes, you can directly use it in the AnQiCMS (or similar Django) template engine{% if 变量名 %}to make a judgment. If the variable is an empty string, an empty array,nilor a boolean valuefalse, the condition will be `

Related articles

What does the `get_digit` filter return when it encounters a non-existent position?

AnQiCMS (AnQiCMS) leverages the efficient characteristics and flexible template engine of the Go language to provide strong support for content management.During template development, we often use various filters to format and process data.Among them, the `get_digit` filter is a utility used to extract a specific digit from a number.Then, how will it respond when we use it to extract a digit from a number at a position that actually does not exist?Let's delve deeper into it.

2025-11-06

How to accurately extract a specified digit from a number in Anqi CMS template?

In the template world of AnQi CMS, efficiently and flexibly handling data is the key to website operators improving the expression of content.As an experienced website operations expert, I know the power of template language lies in its ability to transform complex technical logic into simple and practical content presentation.Today, we will focus on a seemingly simple but extremely practical need: how to accurately extract the digit you want from a number in the Anqi CMS template.

2025-11-06

What is the actual difference between the `default` and `default_if_none` filters when handling variable default values?

In the AnQi CMS template world, we often encounter situations where variables may not have values.For example, the nickname of the user may be empty, the introduction of the article may not be filled in, or a certain configuration item may not exist at all.At this time, in order to make the page display more friendly and information more complete, we need to set up a 'backup' for these variables - that is, the default value.

2025-11-06

How to set a reliable default value for empty variables in Anqi CMS template?

As an experienced website operations expert, I know that handling null variables is the key to ensuring the quality of website content and user experience when building and maintaining website templates.In AnQiCMS such a flexible and efficient content management system, the flexible use of template variables is its strong point, but at the same time, how to elegantly set reliable default values for possibly empty variables to avoid ugly blank spaces on the page or functional anomalies is an art worth in-depth exploration.

2025-11-06

How to use the `{% for ... in ... %}` tag in AnQiCMS templates to iterate over a data list?

How to flexibly use `{% for ...` in Anqi CMS templatein ...How to iterate over a data list with `%}` tag?As an experienced website operations expert, I fully understand the importance of an efficient and flexible template system for content management.AnQiCMS, as an enterprise-level content management system based on the Go language, draws on the essence of the Django template engine in template design, especially its powerful data traversal capabilities, particularly `{% for ...in ...The `tag is one of the core tools for building dynamic page content.

2025-11-06

How to get the index starting from 1 in the current iteration of the `for` loop?

## How to skillfully use AnQiCMS template to easily get the "first" and "Nth" indices in the loop In website content operation, we often need to display a series of contents on the page, such as article lists, product displays, navigation menus, etc.In order to better present the content, we often need to fine-tune the control of each item in the list, such as adding special styles to the first item, or displaying the item's serial number in the list.

2025-11-06

How to get the remaining number of items in the current iteration of the `for` loop (reverse index)?

As an experienced website operations expert, I know that the template function of the content management system is the core of flexible and diverse content display on the website.AnQiCMS (AnQi CMS) leverages the efficient features of the Go language and the Django-like template syntax, providing us with powerful content operation support.Today, let's delve deeply into a practical skill often encountered in template development: how to elegantly obtain the remaining items of the current iteration in the `for` loop, which is what we often call the 'reverse index'.

2025-11-06

How to elegantly display a 'no content' prompt when using the `empty` tag in AnQiCMS `for` loop?

In the daily operation of the website, we understand that the way content is presented is crucial to user experience.A well-designed website that not only provides rich information but also gives users friendly prompts when content is missing, avoiding the embarrassment of blank pages or error messages.

2025-11-06