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, and perform different operations based on this in the template, Anqi CMS template tags and filters provide a straightforward and efficient solution.
Flexible control of content display: The importance of length judgment
Imagine that you are designing a product detail page, which includes a product description.Some product descriptions may be long and require a "View More" button; while some product descriptions may be just a few words and can be displayed directly.Or, a thumbnail field on a list page, you want to display a default placeholder when there is no image, and show the actual image only when there is one.In these scenarios, it is especially critical 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 Tools:lengthFilter
In the Anqi CMS template, to get the length of a variable, we can use the built-inlengthFilter. This filter is very general and can be used to get the number of characters in a string, the number of elements in an array (or slice), or the number of entries in a key-value pair (map).
The usage is very simple, just need to pass the variable through the pipe symbol|Pass tolengththe filter:
{{ 变量名|length }}
For example, if you have an article titleitem.Titleand want to know its length:
<p>文章标题的长度是:{{ item.Title|length }}</p>
Ifitem.TitleIt is 'AnQi CMS is a powerful system', then the output will be11(Both Chinese and English are counted as one character).
A more direct comparison:length_isFilter
In addition to getting the length, Anqi CMS also provides a more direct filterlength_isIt can directly determine if the length of a variable is equal to the number you expect. This filter will return a boolean value (trueorfalse),which is very suitable for use in conditional statements.
The usage is as follows:
{{ 变量名|length_is:期望值 }}
For example, check a list of imagesitem.Imagesif it is empty (i.e., if the length is 0):
<p>图片列表是否为空?{{ item.Images|length_is:0 }}</p>
Ifitem.Imagesis an empty array, it will outputtrue.
combined with conditional statementsifto make a judgment
Masteredlengthandlength_isAfter filtering, we can seamlessly integrate them into the conditional statements of the Anqi CMS template.{% if %}To achieve complex display logic.
1. UselengthCombined with comparison operators.
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.DescriptionThe length exceeds 100 characters, then 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 display the carousel component, otherwise only display one image:
{% 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 determining if the length is exactly equal to a certain value.
For example, to judge a custom fieldcustom_featureswhether it contains 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 practical application scenarios
Avoid empty content area:If a certain area of a page (such as "Latest Comments
lengthDetermine the length of the data list. If the length is 0, display 'No content available' or completely hide the area instead of showing a blank 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 %}Adjust styles or class names:Add different CSS classes based on the length of the variable content to achieve responsive or visual adjustments. For example, if the title is too long, give it a
long-titleClass name to reduce font size:<h1 class="{% if item.Title|length > 30 %}long-title{% endif %}">{{ item.Title }}</h1>Display logic of form fields:Although front-end validation is more common, in some cases, the template can decide whether to display specific prompt information or input box type based on the data passed from the back-end (for example, whether the default value of a certain text input box is empty).
Precautions
When usinglengthorlength_isFiltering, please ensure that the variable you are handling is a string, array (slice), or key-value pair (map) type. For other types, such as plain numbers or boolean values, use directlylengthIt may not have actual significance or may produce unexpected results. However, the template engine of Anqi CMS usually handles these situations intelligently, such as fornilundefined variables,lengthIt often returns 0, which is expected in many judgment scenarios.
The 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.
Common Questions (FAQ)
Q1: If the variable itself isnil(空值)或者未定义,lengthwhat will the filter return?
A1: In the template of AnQi CMS, if the variable isnilor an undefined empty value,lengththe filter usually treats it as a string 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 filters be used for?
A2:lengthThe filter in the Safe CMS also applies to counting the number of entries in the key-value pair (map). For example, if you have multiple custom parameters inmapa variable, you 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, between 5 and 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 allows you to precisely control the display range of content length.