How to use the `length_is` filter in an Anqie CMS template to validate the length of user input or data lists and return a boolean value for conditional rendering?

Calendar 👁️ 62

In AnQi CMS template development, flexibly controlling the display of content is the key to improving the user experience of the website. Among them,length_isA filter is a very practical tool that can help us easily validate user input or the length of data lists in templates, and conditionally render based on the validation results.

length_isThe core function of the filter is to determine whether the length of a variable (whether it is a string, array, or map) is equal to a preset value. It does not directly return the specific length value, but provides a concise and clear boolean result -True(true) orFalse(False). This ability to judge between 'yes' or 'no' makes it an ideal choice for implementing conditional logic in the template.

The usage of this filter is very intuitive: you just need to combine the variable to be checked with the filter and specify an expected length value after the colon. For example,length_iscombine the filter and specify an expected length value after the colon. For example,{{ 变量 | length_is: 期望长度 }}Here, the 'expected length' can be either a number or a string representing a number.It should be noted that for string type data, it will calculate the actual number of characters (even for Chinese characters, they are counted as one character).For array (or Go language slice) and map type data, it calculates the number of elements contained in it.

length_isThe boolean value returned by the filter is the foundation of its powerful functions. When we use it in the template,{% if %}When a tag makes a conditional judgment, this boolean value can directly determine whether a segment of HTML code should be rendered on the page.This allows us to dynamically adjust the page layout and display content based on the length of the data, thus achieving a more intelligent and user-friendly user interface.

Imagine, in your Anqi CMS website, there are many scenarios that need to be rendered conditionally based on the length of the data:

Scenario 1: Verify the length of the user input

Assuming you are on a comment form or user registration page, you want to remind the user that the username or comment content they enter must meet specific length requirements. Bylength_isFilter, you can easily implement this feature.

{# 假设 username 是用户输入的用户名变量 #}
{% if username|length_is:5 %}
    <p class="success-message">您输入的用户名长度符合要求。</p>
{% else %}
    <p class="error-message">用户名长度不正确,请确保为5个字符。</p>
{% endif %}

This code will checkusernameIs the length of the variable exactly 5? If so, display a success message; otherwise, display an error prompt.

Scenario two: Render based on the number of elements in the data list

When you display a list of articles, products, or tags on a page, you may want to adjust the display style or prompt information based on the number of elements in the list.For example, if a list is empty, you may want to display 'No content available';If the list only has a few items, you might want to prompt the user to view more.

{% archiveList articles with type="list" limit="10" %}
    {% if articles|length_is:0 %}
        <div class="empty-list">
            <p>当前没有找到任何文章。</p>
            <a href="/post-article" class="btn btn-primary">立即发布文章</a>
        </div>
    {% elif articles|length_is:1 %}
        <div class="sparse-list">
            <p>文章数量较少,仅有一篇。期待更多精彩内容!</p>
            <ul>
                {% for item in articles %}
                    <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
                {% endfor %}
            </ul>
        </div>
    {% else %}
        <ul class="article-list">
            {% for item in articles %}
                <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
            {% endfor %}
        </ul>
    {% endif %}
{% endarchiveList %}

This template code first attempts to retrieve up to 10 articles. Then, it useslength_isThe filter determines whether the article list is empty or has only one article, and renders different prompts and layouts accordingly. If there are more than one article, it is displayed in a conventional list format.

Scene three: Adjust styles based on the number of tags

Suppose you want to add a unique visual identifier to articles with a specific number of tags.

{% tagList tags with itemId=archive.Id limit="5" %}
    {% if tags|length_is:3 %}
        <div class="tags-container special-highlight">
            {% for tag in tags %}
                <span class="tag-item">{{ tag.Title }}</span>
            {% endfor %}
            <p>这篇文章有3个精选标签!</p>
        </div>
    {% else %}
        <div class="tags-container normal-style">
            {% for tag in tags %}
                <span class="tag-item">{{ tag.Title }}</span>
            {% endfor %}
        </div>
    {% endif %}
{% endtagList %}

In this example, if the number of tags associated with the current article is exactly 3, then the tag container will apply a style namedspecial-highlightand display additional information.

It is not difficult to see through these actual exampleslength_isThe filter plays a powerful role in the Anqi CMS template. It provides a concise and effective way to make logical judgments based on data length, thereby helping you build a more flexible, responsive and user-friendly website.Remember when in uselength_isIt focuses on judging the precise length equality rather than size comparison.


Frequently Asked Questions (FAQ)

  1. length_isFilters andlengthWhat are the differences between filters? lengthA filter used to obtain the actual length of a variable (for example, the number of characters in a string or the number of elements in an array), and returns a number. Whilelength_isAnother filter is used to determine whether the length of a variable isequalsA specified value is returned directlyTrueorFalseA boolean value that does not return specific length values. Therefore,lengthIt is usually used to obtain and display length, whilelength_isit is specifically used for conditional judgment.

  2. length_isCan you determine the length of a number? For example, a number123The length is3? length_isThe filter is mainly used to determine the number of elements in a string, array (slice), or map. It will not convert the number itself to a string before determining the length. For example,{{ 123|length_is:3 }}The result isFalse. If you really need to judge the 'digit' length of a number, you can first convert the number throughstringformata filter to a string, and then uselength_isa filter to judge, for example{{ number|stringformat:"%v"|length_is:3 }}.

  3. How do I judge if the length is 'greater than', 'less than', or 'not equal' to a certain value, instead of 'equal'? length_isThe filter can only judge whether it is 'equal' to the specified length. If you need to perform 'greater than', 'less than', or 'not equal' comparisons, you can first uselengthThe filter gets the actual length of the variable and then combines{% if %}The comparison operator in the tag (such as>/</!=) to make a judgment. For example, to determine if the list length is greater than 5:{% if articles|length > 5 %}.

Related articles

The `length` filter calculates the length of Chinese string in an AnQi CMS template, is it counted by bytes or characters? How does it affect the output?

In AnQi CMS template development, dealing with string length is a common requirement.When dealing with multilingual content, especially when it includes Chinese characters, how a string's length is calculated in bytes or characters can directly affect the accuracy of template output and the presentation of the content.The `length` filter used in the Anqi CMS template is designed to solve this problem.It counts the length of the string by characters rather than by bytes.This means, whether it is an English letter

2025-11-08

How to use the `get_digit` filter to extract a specific digit from a long numeric ID and display or perform logical operations in an Anqi CMS template?

In the development of Anqi CMS templates, we sometimes encounter situations where we need to extract a certain number of digits from a long numeric ID.For example, you may want to assign different styles to content based on some number of the ID, or make some logical judgments.At this time, the `get_digit` filter can be used.It provides a concise and efficient way to achieve this goal, making your template logic more flexible.

2025-11-08

In the Anqi CMS template, what is the difference between the `default` and `default_if_none` filters when the variable is `nil` or empty?

During the template creation process of AnQi CMS, flexibly using variables and their default values is the key to improving the robustness and user experience of the template.When you are dealing with a variable that may not exist (`nil`) or is empty, the `default` and `default_if_none` filters are the tools you commonly use.Although they can all provide an alternative output when the variable 'no value' occurs, their criteria for determining 'no value' are subtle and important.To understand the difference between the two

2025-11-08

The `stringformat` filter supports which formatting verbs in Go? How to choose the most suitable output format in AnQi CMS template?

In Anqi CMS template, the precise display of data is a key factor in improving user experience and website professionalism.The `stringformat` filter is exactly such a tool, allowing us to format various types of data in a highly flexible way to meet diverse front-end display requirements.It draws inspiration from the powerful `fmt.Sprintf` syntax in Go language, allowing developers and content operators to accurately control the format of the output content.###

2025-11-08

How to use the `divisibleby` filter in AnQi CMS template to achieve alternate row coloring or group output every N elements?

In website operation, a well-designed page layout and content display can significantly improve user experience and readability.Especially in scenarios with a long list of items, if all entries are presented in the same style, it is easy to cause visual fatigue.At this time, alternating line colors or grouping by a specific quantity can well solve these problems.

2025-11-08

In addition to `stampToDate`, how can the `date` filter of Anqi CMS implement custom date and time formatting when handling `time.Time` type?

In Anqi CMS, the display of dates and times often needs to be adjusted flexibly according to the actual needs of the website.We all know that the `stampToDate` filter is very convenient for handling Unix timestamps, as it can easily convert a string of numeric timestamps into the date format we need.But sometimes, the date value we handle in the template may already be a `time.Time` type object in Go language, rather than the original timestamp.In this case, Anqi CMS provides another powerful tool, that is `date`

2025-11-08

How to format Unix timestamp to 'YYYY-MM-DD HH:MM' and other localized date strings using the `stampToDate` filter in AnQi CMS?

In website content management, the display of date and time information is ubiquitous.Whether it is the publication time of the article, the listing date of the product, or the submission time of the comments, a clear and readable date format is crucial for improving user experience.AnQiCMS (AnQiCMS) fully understands this need and provides powerful template tags and filters, among which the `stampToDate` filter is a powerful tool to convert the original Unix timestamp into a localized date string that we are familiar with.This article will delve into the usage of the `stampToDate` filter

2025-11-08

How to safely use the `truncatechars_html` filter in Anqi CMS template to truncate HTML rich text content and automatically close tags?

In website content operation, we often need to display the partial content of articles, products, or single pages on list pages, abstract areas, or specific blocks.This content is often rich text that includes HTML tags. Simply truncating by character count may cause the HTML tags to be cut off, thereby破坏页面布局和显示效果.For example, a `<p>This is a paragraph<strong id=“test”>bold</span>` content that is abruptly truncated may cause the page to display unclosed tags.

2025-11-08