How to determine if the length of a variable in the AnQiCMS template matches the expected value and make a judgment in the conditional statement?

In website content management, flexibly controlling the display of content is crucial for improving user experience and page aesthetics.AnQiCMS provides a powerful template engine that allows us to easily determine how to display page elements based on the characteristics of the content, such as the length of a variable.When you need to judge whether the length of a variable meets the expected requirements and perform different operations in the template based on this, the template tags and filters of Anqi CMS provide intuitive and efficient solutions.

Flexibly control content display: The importance of length judgment.

Imagine you are designing a product detail page, which includes product descriptions.Some product descriptions may be long and require a "View More" button;And some product descriptions may only have a few words, they can be displayed directly.Or, a thumbnail field on a list page, you would like to display a default placeholder when there is no image, and the image itself when there is an image.In these scenarios, it is particularly important to judge the length of variables.It helps us avoid displaying blank areas, optimize the layout, and adjust the display strategy according to the richness of the content, ensuring that the presentation of the website content is always just right.

Core Tool:lengthFilter

In AnQi CMS template, to get the length of a variable, we can use the built-inlengthFilter. This filter is very versatile, it can be used to get the number of characters in a string, the number of elements in an array (or slice), or even the number of entries in a key-value pair.

The usage is very simple, just pass the variable through a pipe|pass tolengthfilter:

{{ 变量名|length }}

For example, if you have an article titleitem.Titleand want to know its length:

<p>文章标题的长度是:{{ item.Title|length }}</p>

Ifitem.TitleIs "AnQi CMS is a powerful system", then the output will be11(Chinese and English are counted as one character each).

A more direct comparison:length_isFilter

In addition to getting the length, Anqi CMS also provides a more direct filterlength_isIt can directly determine whether the length of a variable is equal to the numerical value you expect. This filter returns a boolean value (trueorfalse), which is very suitable for use in conditional statements.

How to use:

{{ 变量名|length_is:期望值 }}

For example, check a list of imagesitem.ImagesIs it empty (i.e., the length is 0):

<p>图片列表是否为空?{{ item.Images|length_is:0 }}</p>

Ifitem.ImagesIt is an empty array, it will output:true.

Combined with conditional statementsifMake a judgment

Masteredlengthandlength_isAfter the filter, we can seamlessly integrate them into the conditional statements of the Anqi CMS template{% if %}In which, complex display logic can be achieved

1. UselengthThe filter in conjunction with the comparison operator

When you need to judge whether the length is greater than, less than, or not equal to a certain value,lengththe filter combined with comparison operators (such as>/</==/!=) is very practical.

For example, if a description of an articleitem.DescriptionIf the length exceeds 100 characters, display a 'Read More' link:

{% if item.Description|length > 100 %}
    <p>{{ item.Description|truncatechars:100 }}...</p> {# 使用 truncatechars 过滤器截断文本 #}
    <a href="{{ item.Link }}">阅读全文</a>
{% else %}
    <p>{{ item.Description }}</p>
{% endif %}

For example, if a product has multiple carousel images (item.ImagesThe array length is greater than 1, then the carousel component is displayed, otherwise only one picture is displayed:

{% if item.Images|length > 1 %}
    <div class="product-carousel">
        {% for image in item.Images %}
            <img src="{{ image }}" alt="{{ item.Title }}">
        {% endfor %}
    </div>
{% elif item.Images|length == 1 %}
    <img src="{{ item.Images[0] }}" alt="{{ item.Title }}">
{% else %}
    <img src="/static/images/placeholder.webp" alt="无图片">
{% endif %}

2. Uselength_isThe filter directly determines equality

length_isThe filter returns a boolean value directly, making the code more concise when checking if the length is exactly equal to a certain value.

For example, to check if a custom fieldcustom_featurescontains any content:

{% if custom_features|length_is:0 %}
    <p>该产品暂无特色功能介绍。</p>
{% else %}
    <div class="features-list">
        <h3>产品特色:</h3>
        <ul>
            {% for feature in custom_features %}
                <li>{{ feature }}</li>
            {% endfor %}
        </ul>
    </div>
{% endif %}

Examples of actual application scenarios

  • Avoid empty content area:If a certain area of a page (such as "Latest Comments", "Related Articles") needs to dynamically load data from a database but may not return any data, you can uselengthDetermine the length of the data list. If the length is 0, display 'No content' or completely hide the area instead of showing an empty area that looks like an error.

    {% archiveList relatedArchives with type="related" limit="5" %}
        {% if relatedArchives|length > 0 %}
            <div class="related-articles">
                <h3>相关文章</h3>
                <ul>
                    {% for article in relatedArchives %}
                        <li><a href="{{ article.Link }}">{{ article.Title }}</a></li>
                    {% endfor %}
                </ul>
            </div>
        {% endif %}
    {% endarchiveList %}
    
  • Dynamically adjust the style or class name:Add different CSS classes to elements based on the length of the variable content to achieve responsive or visual adjustments. For example, if the title is too long, give it onelong-titleClass name to reduce font size:

    <h1 class="{% if item.Title|length > 30 %}long-title{% endif %}">{{ item.Title }}</h1>
    
  • Form field display logic:Although front-end validation is more common, in some cases, the template can decide whether to display specific prompts or input box types based on the data passed from the back-end (for example, whether the default value of a text input box is empty).

Points to note

While usinglengthorlength_isWhen filtering, make sure the variables you are handling are of string, array (slice) or key-value pair (map) type. For other types, such as plain numbers or boolean values, use them directlylengthMay not have actual meaning or may result in unexpected outcomes. However, the Anqi CMS template engine usually handles these situations intelligently, such as fornilor undefined variables,lengthIt often returns 0, which is expected in many judgment scenarios.

Anqi CMS provides something likelengthandlength_issuch practical filters, combined with flexibleifConditional statements allow website operators and template developers to finely control the display logic of content, building more intelligent and user-friendly user interfaces.


Frequently Asked Questions (FAQ)

Q1: If the variable itself isnil(Empty value) or undefined,lengthwhat will the filter return?

A1: In Anqi CMS templates, if a variable is,nilor an undefined empty value,lengththe filter will usually consider it to be of length0This means you can use{% if 变量名|length > 0 %}or{% if 变量名|length_is:0 %}to safely check if a variable contains any content.

Q2: Besides strings and arrays,lengthwhat other data types can the filter be used for?

A2:lengthThe filter in AnQi CMS is also used to calculate the number of entries in key-value pairs (map). For example, if you have a variable containing multiple custom parameters,mapyou can use{{ customParams|length }}Get the total number of parameters.

Q3: How do I determine if the length of a string is within a specific range (for example, 5 to 10 characters)?

A3: You can use them togetherlengthFilters and logical operatorsandTo make this judgment. For example:

{% if item.Title|length >= 5 and item.Title|length <= 10 %}
    <p>标题长度在5到10个字符之间。</p>
{% else %}
    <p>标题长度不符合要求。</p>
{% endif %}

This way, you can precisely control the display range of content length.