How to use the `filter-length_is` filter in AnQiCMS templates for `if` judgment of the exact length of a collection?

Calendar 👁️ 58

Precise control and intelligent presentation: AnQiCMS template infilter-length_isEfficient application of filters

In AnQiCMS template development practice, we often need to control the displayed data in detail to ensure the accurate transmission of content and the elegant presentation of the user interface.AnQi CMS, with its efficient architecture based on Go language and the flexible syntax of Django template engine, provides powerful tools for content operators and developers. Among them,filter-length_isFilter is an unsung yet powerful helper that allows us to accurately determine whether a collection (whether it is a string, an array, or a key-value pair) has the specific length we expect in a template, and based on this, we can conditionally render to achieve more intelligent and dynamic content display.

Imagine you are building a product showcase page for a corporate website, and you need to ensure that a special layout is used when the product tag (Tag) list has exactly three tags;Or in a user comment section, you want to display 'No comments' when there are no comments, and only load more features when the number of comments reaches a certain threshold.These seemingly simple requirements cannot do without the precise judgment of the length of the data set.filter-length_isThe filter is exactly for this, it is in the form of a boolean value (TrueorFalse) that clearly tells us whether the length of the target set matches the given number exactly, making it{% if %}The ideal partner of a conditional statement.

Understandingfilter-length_isThe working principle

To effectively use.filter-length_isFirstly, you need to understand its core function: it does not return the actual length of the set, but compares it with the number you specify. If they are completely consistent, it returnsTrue; otherwise, it returnsFalseThis binary judgment feature makes it very suitable as a trigger for conditional logic.

This filter can handle various types of collections:

  • String:It calculates the actual number of UTF-8 characters in a string. An English letter is counted as one character, and a Chinese character is also counted as one character. For example,"AnQiCMS"the length is 7,"安企CMS"The length is 5.
  • Array (Slice):It will calculate the number of elements in the array.
  • Key-value pair (Map):It will calculate the number of key-value pairs.

It is worth noting that,filter-length_isCannot be used directly to judge the 'value' of pure numbers, it is always used to judge the 'length'. For example,{{ 5|length_is:1 }}It will returnFalsebecause the number5is not a string or a collection of length 1.

filter-length_isApplication scenarios

In AnQiCMS template development,filter-length_isHelp us build a flexible and varied user interface:

  1. Precisely control the layout:Assuming your content model allows users to upload 3 cover images.You may want to use a special image gallery layout when the user has just uploaded 3 images;When less than or more than 3 cards, the default layout is used.

    {% archiveDetail archiveImages with name="Images" %}
    {%- if archiveImages|length_is:3 %}
        <div class="gallery-three-column">
            {%- for img in archiveImages %}
                <img src="{{ img }}" alt="封面图" class="gallery-item" />
            {%- endfor %}
        </div>
    {%- else %}
        <div class="gallery-default">
            {%- for img in archiveImages %}
                <img src="{{ img }}" alt="封面图" class="default-item" />
            {%- endfor %}
        </div>
    {%- endif %}
    {% endarchiveDetail %}
    
  2. Elegantly handle empty content:This isfilter-length_isOne of the most common uses. When you retrieve a possibly empty list from the background, you can use it to decide whether to display the list content or a friendly prompt.Although AnQiCMS's{% for %}a loop that{% empty %}Labels can be used to handle empty lists, but they are particularly flexible when dealing with more complex conditions (such as when the list is not empty but does not meet specific length requirements).length_is:0It becomes particularly flexible.

    {% archiveList relatedArticles with type="related" limit="5" %}
    {%- if relatedArticles|length_is:0 %}
        <p>暂无相关文章,敬请期待。</p>
    {%- else %}
        <h3>相关文章推荐</h3>
        <ul>
            {%- for article in relatedArticles %}
                <li><a href="{{ article.Link }}">{{ article.Title }}</a></li>
            {%- endfor %}
        </ul>
    {%- endif %}
    {% endarchiveList %}
    
  3. Form input length validation (front-end prompt):Although the actual form validation should be performed on the backend, providing immediate feedback on the frontend can enhance user experience. For example, if a phone number field requires accuracy to 11 digits, you can assist with the following hints:

    {% set phoneNumber = "13800138000" %} {# 假设这是用户输入的值 #}
    {%- if phoneNumber|length_is:11 %}
        <p class="text-success">手机号码格式正确。</p>
    {%- else %}
        <p class="text-danger">手机号码必须是11位数字。</p>
    {%- endif %}
    

CombineifLabel usage example

filter-length_isThe most common usage is to combineifThe label for conditional judgment. The following are some typical template code snippets that demonstrate this powerful combination:

Determine the exact length of a string variable:

{% set websiteName = "AnQiCMS" %}
{%- if websiteName|length_is:7 %}
    <p>网站名称刚好是7个字符。</p>
{%- else %}
    <p>网站名称的长度不是7个字符。</p>
{%- endif %}

{% set chineseString = "安企内容" %}
{%- if chineseString|length_is:4 %}
    <p>中文字符串长度为4。</p>
{%- else %}
    <p>中文字符串长度不为4。</p>
{%- endif %}

Determine the exact length of an array (slice):

{% set topCategories = ["文章", "产品", "服务"]|list %} {# 假设这是一个通过|list过滤器创建的数组 #}
{%- if topCategories|length_is:3 %}
    <nav class="main-nav">
        {%- for cat in topCategories %}
            <a href="#">{{ cat }}</a>
        {%- endfor %}
    </nav>
{%- elif topCategories|length_is:0 %}
    <p>导航列表为空。</p>
{%- else %}
    <p>导航列表的长度不为3。</p>
{%- endif %}

By these examples, we can clearly seefilter-length_isHow to bring more advanced logical control capabilities to the AnQiCMS template.It makes our template no longer just a simple data display, but able to intelligently adjust its own behavior according to the subtle changes in the data, thereby providing users with a better and more personalized browsing experience.When developing custom templates or maintaining existing sites, it is reasonable to utilizefilter-length_isIt can undoubtedly make your work twice as efficient, building a more responsive and smooth AnQiCMS website.


Frequently Asked Questions (FAQ)

**1.filter-length_isandlengthWhat is the filter?

Related articles

How to use the `filter-divisibleby` filter to determine the divisibility of a number in an `if` statement?

In AnQiCMS template development, achieving dynamic content display and fine-grained control is a daily challenge for website operation experts.AnQiCMS is highly praised for its concise and efficient template engine, which inherits the elegant style of Django templates, making content display and logical control intuitive.In website operation, we often need to present different content or styles based on the characteristics of numbers, such as displaying an advertisement every few products or setting different background colors for odd and even rows of the list.At this time, the `divisibleby` filter can be perfectly combined with the `if` statement

2025-11-06

How to use the `filter-contain` filter in AnQiCMS to check string or array containment in the `if` statement?

As an experienced website operations expert, I fully understand that in an increasingly complex network environment, efficient content management and flexible page display are crucial for improving user experience and SEO effectiveness.AnQiCMS (AnQiCMS) provides a series of practical tools with its high-performance architecture based on the Go language and the powerful features of the Django template engine.

2025-11-06

How to use the `if` tag in combination with `forloop.Counter` to alternate the odd and even row styles of list items?

As an experienced website operation expert, I fully understand how to enhance user experience through detailed interface design in content presentation.AnQiCMS, with its high-performance architecture based on Go language and flexible template engine, provides us with great freedom to easily implement all kinds of creativity and features.

2025-11-06

How to elegantly handle empty list situations in AnQiCMS template using the `{% for ... empty ... %}` syntax?

In AnQiCMS template development, we often need to display a series of content lists, such as article lists, product lists, navigation menus, or friend links.However, these lists are not always filled with data. When the list is empty, how to elegantly inform the user that "there is no content here" instead of displaying a blank page or an error message has become a detail consideration in template design.AnQi CMS is well-versed in this, drawing on the excellent design of Django templates in its powerful template engine developed in Go language, providing us with `{% for ...

2025-11-06

What is the difference in handling variable null values between `filter-default` and `filter-default_if_none` in `if` condition judgments?

AnQiCMS (AnQiCMS) is a powerful assistant for our daily content operation, with its flexible template engine syntax making content display diverse and efficient.However, in practice, we often encounter situations where variable values are empty, such as when the article title is not filled in, or when a custom field has no data.How elegantly to handle these 'null' values to ensure that the website front-end display is always professional and friendly has become a topic that content operators must face.

2025-11-06

How does the `filter-yesno` filter help AnQiCMS templates handle the tri-state logic of 'yes/no/unknown'?

As an experienced website operations expert, I know that how to present data status efficiently and clearly in a content management system is one of the keys to successful operations.AnQiCMS (AnQiCMS) provides an excellent solution in this aspect with its flexible template engine and rich built-in filters.Today, let's delve into a seemingly simple yet powerful filter——`filter-yesno`, and how it helps AnQiCMS templates handle complex ternary logic such as 'yes/no/unknown'.

2025-11-06

How to load different layouts in AnQiCMS templates based on the current template type (such as `template_type`)?

In the practice of AnQiCMS (AnQiCMS), flexible template management is a key link in the efficient operation of the website.As an experienced website operations expert, I am well aware of how to load the appropriate layout for different scenarios, which not only optimizes user experience but also enhances the website's response speed and maintenance efficiency.Today, let's delve deeply into how to cleverly load different layout strategies in the AnQiCMS template, such as `template_type`.

2025-11-06

The AnQi CMS template development tool: gracefully handle missing files using the `if_exists` parameter of the `include` tag

As an experienced website operations expert, I know how important efficiency and stability are in building and managing corporate websites.AnQiCMS (AnQiCMS) boasts its high-performance architecture based on the Go language and a flexible template system, providing us with powerful content management capabilities.In daily template development, the `include` tag is undoubtedly our powerful assistant for achieving modularization and improving code reusability.However, convenience also hides a small trap: if the template file referenced by `include` is unfortunately missing, the website page will immediately throw an error, affecting user experience

2025-11-06