How to judge whether an array or string is empty in AnQiCMS template using the `length` filter?

Calendar 👁️ 70

In Anqi CMS template development, we often need to decide the display content of the page based on the existence or absence of data, such as an article list. If the list is empty, we may need to display "No content" instead of a blank area. At this point,lengthThe filter becomes our powerful assistant, it helps us easily judge whether arrays, strings, and other data are empty.

Get to knowlengthFilter

lengthThe filter is a very practical feature provided by the Anqi CMS template engine, its main function is to return the length of a variable. This 'length' varies depending on the type of the variable:

  • For strings: lengthCalculates the actual number of characters in a string. Whether it is an English letter, number, or Chinese character,lengthit is counted as a character.
  • For an array or slice (Slice): lengthReturns the total number of elements contained in the array or slice.
  • For a key-value pair (Map): lengthIt will return the number of key-value pairs.

Its basic usage syntax is very intuitive:

{{ 变量 | length }}

For example, if your template contains a stringsomeText = "Hello AnQiCMS"then{{ someText|length }}will output13. If the string ischineseText = "你好安企CMS"then{{ chineseText|length }}it will also be output6. This reflects its friendly support for multilingual characters. Similarly, if there is an arraymyList = ["item1", "item2"],{{ myList|length }}It will return2.

How to determine if an array or string is empty

MasteredlengthAfter the basic usage of the filter, we can use it flexibly in the scenario of determining if data is empty.

1. Check if a string is empty

There are two very convenient ways to check if a string is empty:

Method one: uselengthFilter combinationifStatement.This method directly gets the length of the string and compares it with0Compare. When the length is0it means the string is empty.

{% set articleTitle = "安企CMS模板开发指南" %}
{# 或者 {% set articleTitle = "" %} #}

{% if articleTitle|length == 0 %}
    <p>抱歉,文章标题是空的。</p>
{% else %}
    <h1>{{ articleTitle }}</h1>
{% endif %}

Method two: directly inifthe statement to determine the stringIn AnQi CMS template engine, non-empty strings are considered 'true', and empty strings are considered 'false'. Therefore, you can directly use string variables asifThe condition of the statement.

{% set authorName = "安企小助手" %}
{# 或者 {% set authorName = "" %} #}

{% if authorName %}
    <p>作者:{{ authorName }}</p>
{% else %}
    <p>作者未知。</p>
{% endif %}

This method is usually recommended because it requires less code and is more readable.

2. Check if the array (or slice) is empty.

For arrays or slices, there are many diverse and practical methods to determine if they are empty:

Method one: uselengthFilter combinationifStatement.Similar to strings, obtain the number of elements in the array and determine if it is:0.

{% set productList = ["产品A", "产品B"] %}
{# 或者 {% set productList = [] %} #}

{% if productList|length == 0 %}
    <p>当前没有可用的产品。</p>
{% else %}
    <ul>
    {% for product in productList %}
        <li>{{ product }}</li>
    {% endfor %}
    </ul>
{% endif %}

Method two: useforrepeatedlyemptySyntaxThis is to determine if the list is empty when looping through the list datamost recommendedmethod. Whenforthe data set being looped over is empty,{% empty %}the content inside the block will be executed automatically.

{% set commentList = ["评论1", "评论2"] %}
{# 或者 {% set commentList = [] %} #}

{% for comment in commentList %}
    <div class="comment-item">{{ comment }}</div>
{% empty %}
    <p>目前还没有任何评论。</p>
{% endfor %}

This method perfectly integrates the two logics of 'traversal' and 'no content prompt', making the code structure more compact and clear.

Method three: directly inifthe statement to determine the arrayAs with strings, in AnQi CMS templates, non-empty arrays or slices are considered "true", and empty arrays or slices are considered "false". Therefore, you can also use them directly asifThe condition of the statement.

{% set relatedArticles = [] %}
{# 或者 {% set relatedArticles = ["相关文章1"] %} #}

{% if relatedArticles %}
    <h3>相关推荐</h3>
    <ul>
    {% for article in relatedArticles %}
        <li>{{ article }}</li>
    {% endfor %}
    </ul>
{% else %}
    <p>暂无相关推荐。</p>
{% endif %}

3. Advanced Usage:length_isFilter

Sometimes, we need to not only check if the data is empty but also if its length meets a specific requirement. At this point,length_isThe filter is very useful. It is used to check if the length of a value (which can be a string, array, etc.) isequalsa specified number and returns a boolean valueTrueorFalse.

The syntax is:

{{ 变量 | length_is: 目标长度 }}

For example, if you need to ensure that a navigation menu exactly has 5 items, you can use it like this:

{% set navItems = ["首页", "产品", "服务", "关于我们", "联系我们"] %}
{# 或者 {% set navItems = ["首页", "产品"] %} #}

{% if navItems|length_is:5 %}
    <p>导航菜单刚好有5个项目,布局完美!</p>
{% else %}
    <p>导航菜单项目数量不符合预期。</p>
{% endif %}

Combinelength_is:0It can also achieve the effect of being empty, but it is more common to uselength == 0or directlyifvariable names.

Summary

BylengthThe filter and its related judgment methods allow Anqi CMS users to control the display logic of content more flexibly and accurately in templates.Whether it is simple string or array null judgment, or more complex length matching, these tools can help you build a website page with better user experience and more robust logic.Understanding and proficiently applying these filters is the key to improving the efficiency and quality of AnQi CMS template development

Related articles

How to ensure the correct setting of the `hreflang` tag in the `languages` label of the AnQiCMS multilingual site?

Today, with the deepening of globalization, many enterprises and content operators need to provide customized content for users of different languages or regions.To ensure that these multilingual versions can be correctly identified and displayed to target users, the proper setting of the `hreflang` tag is particularly important.For friends using AnQiCMS to build multilingual websites, the built-in `languages` tag is the powerful tool to solve this problem.Understanding the importance of the `hreflang` tag To delve deeper into

2025-11-09

How to safely embed third-party statistics or advertising JS code in AnQiCMS templates?

In website operation, we often need to rely on third-party statistical tools to analyze visitor behavior, or to generate income through advertising platforms.Embed these third-party JavaScript (JS) codes securely and efficiently into website templates is a skill that every website operator needs to master.For those using AnQiCMS, understanding its template mechanism and built-in features can help us complete this task more securely.AnQiCMS is an enterprise-level content management system developed based on the Go language, which has always paid close attention to performance and security in its initial design

2025-11-09

How to determine if the `Content` field of the document is empty using the `archiveDetail` tag and display alternative content?

How can you elegantly handle the case where the document content is empty in AnQi CMS?During the operation of the website, we often publish various types of documents, which contain important information.However, sometimes for various reasons, such as the content is still in draft stage, data is missing during import, or simply some documents are only titled without detailed text, we may encounter the situation where the `Content` field of the document is empty.If the template does not perform any processing when rendering these document detail pages, the user may see a blank page area, which not only affects user experience

2025-11-09

How to judge whether a custom field exists in the AnQiCMS template and conditionally render according to its value?

In AnQiCMS template development, flexibly displaying content is the key to improving user experience and website professionalism.Among them, judging custom fields and rendering conditions based on their values is an indispensable skill to achieve this goal.In this way, you can ensure the precise display of page content, avoid displaying empty values, or dynamically adjust the page layout and functionality based on specific data.### Understanding AnQiCMS Custom Fields and Their Retrieval Methods in Templates AnQiCMS is a powerful content management system

2025-11-09

How to use the `join` filter in AnQiCMS template to handle empty arrays or arrays with a single element?

In AnQi CMS template development, the flexibility of data display is crucial.We often need to present the data list obtained from the backend in a beautiful and consistent manner on the front-end, which includes the need to concatenate the elements of an array (or list) into a string.The AnQi CMS template engine provides a powerful `join` filter, which not only handles common arrays containing multiple elements but also demonstrates its unique and practical behavior in special cases such as empty arrays or arrays containing only a single element.The `join` filter is a very practical tool in the Anqi CMS template

2025-11-09

How does the `split` filter handle empty strings or strings without the specified delimiter in AnQiCMS templates?

In AnQiCMS template development, string processing is a common requirement.Sometimes we need to split a string containing multiple values into individual items so that they can be traversed on the page for display or further processing.At this time, the `split` filter has become a powerful assistant for template developers.It can split a string into an array (or slice) based on a specified delimiter, greatly simplifying the logic of complex data display.However, some specific scenarios when using the `split` filter may confuse developers who are new to the field

2025-11-09

What is the result of repeatedly outputting an empty string in the `repeat` filter of AnQiCMS templates?

AnQiCMS's template system is renowned for its concise and efficient Django-style syntax, which allows content developers to easily build dynamic pages.In daily template development, we often use various filters to process and format data.Among them, the `repeat` filter is a very practical tool that can repeat a string according to the specified number of times.However, when using the `repeat` filter, some developers may encounter a seemingly simple but easily confusing problem: when

2025-11-09

How to display the detailed structure, type, and value of the `dump` filter in AnQiCMS template debugging?

During the development and maintenance of AnQiCMS templates, we often encounter situations where we need to confirm the content of variables.Improper use of template tags or an unexpected data structure passed from the backend can lead to page display errors.If you can see the internal structure, type, and current value of a variable at this time, it will undoubtedly greatly improve our debugging efficiency.In the AnQiCMS template system, the `dump` filter was born to solve this pain point, it's like a periscope, helping us to understand the 'inner nature' of template variables.### The pain points of template debugging and

2025-11-09