As a website operator who is well-versed in the Anqi CMS, I fully understand the importance of accurately obtaining the length of data in content management and template design.Whether it is 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 language), and key-value pairs (maps or structs in Go language) is the key to improving website user experience and operational efficiency.

In AnQiCMS's powerful template system, we have a simple and efficient method to achieve these length retrievals.This is due to the rich filters and tags provided by its class Django template engine.

灵活驾驭内容:掌握 AnQiCMS 模板中字符串、数组和键值对的长度获取技巧

In website operation, we often need to dynamically adjust the page layout, show or hide certain elements, based on the amount of content.For example, when a blog post has no relevant tags, we may not want to display an empty 'related tags' section; or when displaying a photo gallery, knowing the number of images is necessary to determine pagination or slider styles.It is particularly important to obtain the actual length of strings, arrays, or key-value pairs at this time.AnQiCMS's template engine provides intuitive and powerful tools.

获取字符串的实际长度

For any text content, such as article titles, summaries, or custom fields, we may need to obtain the character count. AnQiCMS templates providelengthThe filter is used to implement this function.

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

{{ archiveTitle|length }}

This will directly outputarchiveTitleThe 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 obtained througharchiveListthe article list obtained by tags,categoryListthe collection of categories obtained,archiveDetailobtainedImages(Image group) field, they are usually in the form of an array (usually a slice in Go language)slice) exist. To get the number of elements in these sets, you can also use)lengthFilter.

Assuming you usearchiveListObtained a set of articlesarchivesand would like to know how many articles are in 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 outputarchivesThe number of elements in the array. This is very useful when you need to judge if the list is empty (usually配合{% if list|length > 0 %}or{% for ... empty ... %}tags), show total statistics, or control pagination logic.

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

In AnQiCMS templates, we sometimes encounter key-value pair data, such as byarchiveParamsLabel acquisition document custom parameters. WhenarchiveParamsBysorted=trueis obtained in the way, it returns an array containing{Name: "", Value: ""}structure object, at this time, the length of the array is obtained.

If a variable directly represents one in 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, througharchiveParamsGet custom parameters and want to know how many custom parameters are 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 }}it will returnparamsArray (or map) entry count. This helps us dynamically display or format these parameters.

Uselength_isFilter for precise length judgment

except for getting the actual length, AnQiCMS template also provides alength_isFilter used to check if the length of a variable is equal to a specific value. This filter is mainly used for strings, returning a boolean valuetrueorfalse.

When you need to strictly judge whether the length of a string meets certain conditions,length_isthe filter 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 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 areasIn rendering modules such as "related articles{{ collection|length == 0 }}Then 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 carousel: When usingImagesField display image, by{{ Images|length }}Get the number of images, which can dynamically adjust the layout of the gallery, the display or hiding of the pagination, and even switch to the default placeholder image when the number of images is insufficient.
  • Form validation promptAlthough AnQiCMS backend has built-in form validation, predicting the length of some user input fields (such as custom message fields) on the front end can provide users with more immediate feedback.
  • SEO Optimization:Dynamic Adjustmentmeta descriptionThe截取length of,Ensure that it conforms to the **practice of search engines, or adjust the reading time estimate according to the number of words in the article content.

By using flexibilitylengthandlength_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,lengthIs the filter applicable to all types of data?

lengthThe filter is mainly used to get the length of the string and the number of elements in an array (slice) or a map (key-value set).It can return the actual size of these iterable or countable Go language data structures.lengthThe filter may not produce the expected results or may trigger template errors.

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

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

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

<li>{{ item.Title }}