In AnQi CMS template development, it is often necessary to dynamically adjust the page display according to the length of the data content.Whether it is to truncate text, judge whether the list is empty, or perform simple content verification, understanding how to obtain the length of a string, array, or key-value pair is the foundation of realizing these functions.lengthandlength_isThese two filters, they can help developers flexibly handle these requirements.
lengthFilter: Get the actual length of the data content.
lengthA filter acts like a ruler, able to precisely tell you the 'size' of the content in the variable. Its usage is very intuitive, simply pass the variable through the pipe symbol|pass tolengththe filter.
String length calculationWhen applied to a string,lengthThe filter calculates the actual number of UTF-8 characters in a string.This means that, whether it is English letters, numbers, or Chinese characters, each character is counted as 1.This is particularly useful for websites that contain multilingual content, as it avoids the bias that may be caused by traditional byte length calculations.
For example, if you have a variableitem.TitleContaining "AnQiCMS", then{{ item.Title|length }}will output4. If the content is "AnQiCMS", it will output the same.7.
Array (Slice) and Map Length CalculationFor an array (also known as slice in Go language) or a map,lengthThe filter will return the number of elements or entries it contains. This allows us to easily know how many items a list has, or how many properties a data object has.
Suppose you have a variable namedtagsAn array variable that contains['网站运营', '模板开发', 'SEO']three elements, then{{ tags|length }}will output3. Similarly, if there is a key-value pairuser_info = {name: '张三', age: 30, city: '北京'}then{{ user_info|length }}will output3.
Usage example:
{# 假设有一个字符串变量 message = "欢迎使用安企CMS" #}
<p>消息内容的字符数:{{ message|length }}</p> {# 输出: 7 #}
{# 假设有一个数组变量 categories = ["新闻", "产品", "关于我们"] #}
<p>分类的数量:{{ categories|length }}</p> {# 输出: 3 #}
{# 假设有一个键值对变量 product_specs = {颜色: "红色", 尺寸: "L", 重量: "2kg"} #}
<p>产品参数的数量:{{ product_specs|length }}</p> {# 输出: 3 #}
length_isa filter: check the specified length of the data content
length_isFilter is onlengthBased on further development, it not only retrieves the length but also compares this length with a value specified by you and ultimately returns a boolean value (trueorfalseThis is very useful when precise length-based conditions need to be judged.
The working principle and limitations
length_isBasic usage is{{ variable|length_is:期望长度 }}. It will checkvariablewhether the length of期望长度Please notelength_isThe filter is mainly designed for string variablesIf you try to apply it to a non-string variable (like a number), even if the length appears to match, it will returnfalse. This is a common misconception, developers should pay special attention when using it.
For example,{{ "hello"|length_is:5 }}will returntrueBut{{ 123|length_is:3 }}it will returnfalsebecause123Is a number, not a string. If you really need to judge the "length" of a number, you should convert it to a string first (although the Anqi CMS template engine does not have a directto_stringFilter, but usually in actual development, it is handled or avoided through other means, and direct comparison is not usually done).
Usage example:
{# 假设有一个字符串变量 username = "admin" #}
{% if username|length_is:5 %}
<p>用户名长度正好是5个字符。</p> {# 输出: 用户名长度正好是5个字符。 #}
{% else %}
<p>用户名长度不是5个字符。</p>
{% endif %}
{# 假设有一个字符串变量 description = "安企CMS是一个强大的内容管理系统。" #}
{% if description|length_is:15 %}
<p>描述内容的字符数正好是15。</p>
{% else %}
<p>描述内容的字符数不是15。</p> {# 输出: 描述内容的字符数不是15。 #}
{% endif %}
Application based on actual scenarios
These filters can play an important role in building dynamic and responsive website templates:
Text truncation and hints:When the title or description of an article is too long, you can use
lengthDetermine whether to truncate and combinetruncatecharsortruncatewordsFilter to display.{% set article_title = "安企CMS:为中小企业赋能的Go语言内容管理系统" %} {% if article_title|length > 20 %} <p>{{ article_title|truncatechars:20 }}...</p> {# 输出:安企CMS:为中小企业赋能的G... #} {% else %} <p>{{ article_title }}</p> {% endif %}Handling when the content is empty:When a list (such as links, image collection) may be empty, you can use
lengthorlength_isJudge and display different content.{% commentList comments with archiveId=archive.Id type="list" limit="10" %} {% if comments|length_is:0 %} {# 或者 comments|length == 0 #} <p>目前还没有评论。</p> {% else %} <ul> {% for comment in comments %} <li>{{ comment.UserName }}: {{ comment.Content }}</li> {% endfor %} </ul> {% endif %} {% endcommentList %}Dynamic styles or layout:Apply different CSS classes based on the number of elements in the list to achieve a more flexible page layout.
{% categoryList categories with moduleId="1" parentId="0" %} {% if categories|length_is:1 %} <ul class="single-category-layout"> {% elif categories|length > 5 %} <ul class="many-categories-layout"> {% else %} <ul class="default-category-layout"> {% endif %} {% for category in categories %} <li><a href="{{ category.Link }}">{{ category.Title }}</a></li> {% endfor %} </ul> {% endcategoryList %}
Masterlengthandlength_isThese simple yet powerful filters allow you to navigate effortlessly in the development of Anqin CMS templates, control the display of content more finely, and thus create more intelligent and user-friendly websites.
Frequently Asked Questions (FAQ)
1.lengthCan the filter correctly calculate the length of a string containing Chinese characters?Yes,lengthThe filter counts the length of a string by UTF-8 character count.This means that a Chinese character and an English character are both counted as 1, ensuring accurate length judgment for multi-language content.
2. Why{{ 5|length_is:1 }}This syntax will returnFalse?
length_isThe filter is specifically designed for comparisonstringlength. When you try to apply it to a number (such as5It does not automatically convert the number '5' to the string '5' before performing the length comparison, but rather directly judges that the type does not meet the string requirement, therefore it returnsFalse. In uselength_isEnsure that you are operating on a string variable when
3. Besideslengthandlength_isWhat filters can help me handle string length or display limits?In addition to these two filters, Anqi CMS also providestruncatecharsandtruncatewordsfilter.truncatecharsUsed to truncate strings by character count and add an ellipsis at the end;truncatewordsIt is used to truncate strings by word count, and ellipses are also added. They are often used withlengthto avoid content overflow or enhance reading experience.