How to get the actual length of a string, array, or key-value pair?

Calendar 👁️ 71

As an experienced website operator familiar with AnQi CMS, I fully understand the importance of accurately obtaining data length in content management and template design.In order to optimize the display layout, implement conditional judgment, or ensure the integrity of the content, having a clear understanding and operational ability of the actual length of strings, arrays (or slices in Go), and key-value pairs (maps or structs in Go) is crucial for improving website user experience and operational efficiency.

In the powerful template system of AnQiCMS, we have a simple and efficient method to achieve the acquisition of these lengths.This is due to the rich filters and tags provided by its Django template engine.

Master the techniques of obtaining the length of strings, arrays, and key-value pairs in AnQiCMS templates: skillfully navigate content

In website operation, we often need to dynamically adjust the page layout, display or hide certain elements according to the amount of content.For example, when a blog article has no related tags, we may not want to display an empty "related tags" area;Or when displaying a photo gallery, it is necessary to know the number of images to determine pagination or slider style.At this point, it is particularly important to obtain the actual length of strings, arrays, or key-value pairs.The template engine of AnQiCMS provides intuitive and powerful tools for this.

Get the actual length of a string

For any text content, such as article titles, summaries, or custom fields, we may need to obtain the number of characters. AnQiCMS templates providelengthA filter is used to achieve this function.

When you need to know the length of a string variable, you can pass it through the pipe symbol directly.|pass tolengthFilter. For example, if you have a custom field namedarchiveTitleThe variable stores the article title, and to get its length, you can write the template code like this:

{{ archiveTitle|length }}

This will output directlyarchiveTitleThe number of characters contained in a variable. This method is very useful when it is necessary to limit the length of text or display statistical information.

Get the number of elements in an array (or slice)

In AnQiCMS, whether througharchiveListlabel to get the article list,categoryListor to get the category set,archiveDetailobtainedImages(Image group) fields are usually in the form of arrays (in Go language, usually slices)slice). To get the number of elements in these collections, you can also uselengthfilter.

Suppose you usearchiveListObtained a set of articlesarchivesAnd you want to know how many articles are on this list, you can use it like this:

{% archiveList archives with type="list" limit="10" %}
    <p>当前列表包含 {{ archives|length }} 篇文章。</p>
    {% for item in archives %}
        <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
    {% empty %}
        <p>抱歉,目前没有可展示的文章。</p>
    {% endfor %}
{% endarchiveList %}

In this scenario,{{ archives|length }}It will output.archivesThe number of elements in the array. This is very useful when you need to judge if the list is empty (usually with{% if list|length > 0 %}or{% for ... empty ... %}tags), display total statistics, or control pagination logic.

Get the number of entries in a key-value pair (Map or a collection of struct fields)

In the AnQiCMS template, we sometimes encounter key-value pair data, such as througharchiveParamsThe label retrieves the custom parameters of the document. WhenarchiveParamsStart withsorted=trueobtained in this way, it returns an array containing{Name: "", Value: ""}an array of struct objects, at which point the length is obtained from the array.

If a variable directly represents a Go languagemaptype, and you want to know how many key-value pairs it contains,lengthThe filter can also be applied directly and return the number of entries in the map.

For example, byarchiveParamsGet custom parameters and want to know how many custom parameters have been defined:

{% archiveParams params with sorted=true %}
    <p>该文档共设置了 {{ params|length }} 个自定义参数。</p>
    {% for item in params %}
        <div>{{ item.Name }}:{{ item.Value }}</div>
    {% endfor %}
{% endarchiveParams %}

Here{{ params|length }}will returnparamsThe number of entries in the array (or map). This helps us dynamically display or format these parameters.

Uselength_isThe filter makes an exact length judgment.

In addition to obtaining the actual length, the AnQiCMS template also provides alength_isA filter used to check if the length of a variable is equal to a specific value. This filter is mainly used for strings and returns a boolean valuetrueorfalse.

When you need to strictly judge whether the length of a string meets certain conditions,length_isfilters can come in handy. For example, check if the username length is 5:

{% if userName|length_is:5 %}
    <p>用户名长度刚好是5个字符。</p>
{% else %}
    <p>用户名长度不等于5个字符。</p>
{% endif %}

This filter makes the condition judgment more intuitive and accurate.

Practical Application and **Practice

Master these length acquisition techniques, and it will greatly enhance your ability to build dynamic and user-friendly interfaces in AnQiCMS.

  • Avoid displaying empty areas.When rendering modules such as "related articles", "latest comments", or "tag cloud", first judge the length of the data set. If{{ collection|length == 0 }}You can choose not to render the module or display a "No data available" prompt to avoid large blank areas on the page and enhance the visual experience.
  • Image gallery and carouselWhen usingImagesField display image, through{{ Images|length }}Get the number of images, which can dynamically adjust the layout of the gallery, the display or hide of the pagination, and even switch to the default placeholder image when the number of images is insufficient.
  • Form validation promptAlthough AnQiCMS has built-in form validation on the backend, front-end prediction of the length of some user input fields (such as custom message fields) can provide users with more immediate feedback.
  • SEO Optimization: Adjust dynamicallymeta descriptionThe length of the截取, ensure it conforms to the search engine's practices, or adjust the reading time estimate according to the number of words in the article.

By flexible applicationlengthandlength_isFilter, we can make the content display of AnQiCMS website more intelligent and user-friendly, providing users with a more perfect browsing experience.


Frequently Asked Questions

In AnQiCMS template,lengthDoes the filter apply to all types of data?

lengthThe filter is mainly used to obtain the length of a string and the number of elements in an array (slices) or a map (key-value collection).It can return the actual size of these iterable or countable Go language data structures.For a single number, boolean, or other non-iterable non-collection type variable, use directlylengthThe filter may not yield the expected results or may trigger template errors.

If I want to check if an array is empty, besideslengthare there any more concise methods?

Yes, AnQiCMS's template engine provides a very concise syntax for handling empty arrays. You can use{% for ... empty ... %}tag structure. WhenforWhen the array variable iterates empty,emptythe content inside the block will be rendered. This is more elegant and semantic than using{% if list|length == 0 %}then write aelseblock.

Example: “`twig {% for item in archives %}

<li>{{ item.Title }}

Related articles

How to determine if a variable is empty in a template and set a default display value?

As an experienced CMS website operation person, I am well aware of the importance of template content robustness for website user experience and data display.In daily operation, we often encounter situations where variables may be empty. If not handled properly, it may result in incomplete page display, or even cause the page to report errors.AnQiCMS (AnQiCMS) offers a flexible template engine with multiple ways to determine if a variable is empty and set a default display value, which is crucial for building high-quality, high-fault-tolerant websites.

2025-11-06

How to convert English string to uppercase, lowercase, or capitalize each word?

As an experienced CMS website operation personnel for an enterprise, I know the importance of the refinement of content presentation in attracting and retaining users.When handling website content, the format of the text often determines its professionalism and readability.AnQi CMS provides a powerful and flexible template engine that can help us easily achieve various text format conversions, such as converting English strings to uppercase, lowercase, or capitalizing the first letter of each word.

2025-11-06

How to remove specified characters or spaces from the beginning, end, or any position of a string?

As an experienced CMS website operation personnel for a security company, I know the importance of content quality and data cleanliness for user experience and SEO optimization.In the daily content publishing and maintenance work, we often encounter the need to clean up strings, such as removing unnecessary spaces and special characters to ensure the standardization and aesthetics of the content.

2025-11-06

How to concatenate the elements of an array into a string using a specified character?

As an experienced soldier in the field of Anqing CMS content management, I know that how to efficiently handle and display data in daily operations is the key to improving website user experience and content value.AnQi CMS provides us with great flexibility with its powerful template engine.Today, we will delve deeply into a very common requirement in content display: how to concatenate multiple elements in an array into a string with a specified character.This is crucial for scenarios such as aggregating display keywords, image lists, or handling multi-select custom fields.

2025-11-06

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

As an experienced CMS website operation person in the security industry, I know that both the accuracy and beauty of data are equally important in content display.Especially for floating-point numbers, how to format them to display with a specified number of decimal places is a key element in improving user experience and ensuring clarity of information.The powerful template engine of AnQi CMS provides flexible filter (filters) functions, allowing us to easily achieve this requirement.

2025-11-06

How to wrap long text content automatically at a specified length?

As an experienced CMS website operation personnel, I fully understand the core status of content in website operation.High-quality content not only requires careful creation, but also needs to be presented in **a way** to ensure the efficiency of user experience and information delivery.How to effectively handle automatic line breaks for long text content is the key to improving the readability and aesthetics of the page.The AnQi CMS maintains the integrity of content storage, but on the front-end display level, it provides flexible automatic line break solutions through its powerful template engine and rich filters.

2025-11-06

How to automatically convert URLs and email addresses in the text content into clickable links?

Today, with the increasing richness and frequent updates of digital content, website operators not only need to pay attention to the quality of the content, but also to the way it is presented and the user interaction experience.When we publish articles, product descriptions, or any text information on AnQiCMS (AnQiCMS), we often include some URL links and email addresses pointing to external resources or contact information.If this information is only displayed in plain text, users will have to manually copy and paste, which undoubtedly increases the complexity of the operation and reduces the user experience.

2025-11-06

How to get the list of related articles for the current article (based on category, keywords, or manual association)?

As a website operator who is deeply familiar with the operation of AnQiCMS, I know that high-quality content and user experience play a key role in the success of a website.Articles related can effectively extend the user's stay on the site, increase page views, and are also very beneficial for the internal link optimization (SEO) of the website.AnQiCMS provides a flexible way to obtain and display these related contents, meeting the operational needs of different scenarios.

2025-11-06