How to truncate long category names in the `categoryList` loop and add an ellipsis?

Calendar 👁️ 56

How to elegantly truncate long category names and add ellipses in AnQi CMS templates

In website operation, the display of category names may seem trivial, but it actually has a significant impact on user experience and page aesthetics.A well-designed website ensures that all its elements can coexist harmoniously, especially the text in the navigation and lists.When the category name is too long, it may cause layout confusion, text overflow, and even poor display on different devices, seriously affecting the user's reading experience.

AnQi CMS with its powerful Go language backend and flexible Django-like template engine provides great convenience for content management.It allows us to finely control content through simple template tags and filters.Today, let's delve into a common scenario: how tocategoryListIn the loop, truncate excessively long category names and cleverly add ellipses to maintain the page's neatness and professionalism.

Understand the template foundation of Anqi CMS.categoryListTag

First, let's quickly review the basic structure of Anqi CMS templates. The Anqi CMS template syntax is similar to Django, using double curly braces{{ 变量名 }}Output the variable value, using curly braces and percent signs{% 标签 %}Execute logical operations, such as loops, conditional judgments, etc.

categoryListTags are the core tools we use to display category navigation or lists on our website. When we usecategoryListTags are looped to output a series ofitemobjects, eachitemIt represents a category, which includes such asTitle(Category name),Link(Category link) core information. Usually, we will traverse and display categories in this way:

{% categoryList categories with moduleId="1" parentId="0" %}
    <ul>
        {% for item in categories %}
            <li>
                <a href="{{ item.Link }}">
                    {{ item.Title }}
                </a>
            </li>
        {% endfor %}
    </ul>
{% endcategoryList %}

This code can successfully list all categories, but when a certainitem.Title(i.e., the category name) is particularly long, the problem arises.

Core solution: usingtruncatecharsa filter to truncate

To solve the problem of long classification names, the template filter built into Anqi CMS comes into play, especiallytruncatecharsthis filter.

truncatecharsThe role of the filter:truncatecharsA filter is specifically used to truncate a string to a specified length, and if the string is actually truncated, it will automatically add an ellipsis at the end....This feature is very effective for maintaining text length consistency while implying that content is omitted.

How to use:truncatecharsThe filter accepts a numeric parameter representing the character length you want to truncate to. For example,item.Title|truncatechars:15will attempt to convertitem.TitleTruncate to 15 characters. If the original string length is less than or equal to 15, it will be output as is; if it is greater than 15, it will be truncated and appended with...Ensure the total length (including the ellipsis) does not exceed the specified value.

Let's apply this filter to ourcategoryListloop:

{% categoryList categories with moduleId="1" parentId="0" %}
    <ul class="category-list">
        {% for item in categories %}
            <li class="category-item">
                <a href="{{ item.Link }}" title="{{ item.Title }}">
                    {# 应用 truncatechars 过滤器截断分类名称 #}
                    {{ item.Title|truncatechars:15 }}
                </a>
            </li>
        {% endfor %}
    </ul>
{% endcategoryList %}

code parsing:

  • {{ item.Title|truncatechars:15 }}: This line is crucial.item.TitleIs the category name string we need to handle.|The symbol is the filter pipe character, it will.item.Titlepass totruncatecharsfilter.:15Then tell.truncatecharsTruncate the string to a maximum of 15 characters.
  • title="{{ item.Title }}"To enhance the user experience, even if the name is truncated, we can stilltitledisplay the full category name when the attribute is hovered over, which is a very friendly practice.

By making this simple modification, all overly long category names will be elegantly truncated, presenting a uniform length visually, greatly enhancing the neatness and professionalism of the page.

Advanced consideration: Dynamic length and HTML content truncation

In practical applications, you may encounter some more complex requirements:

  1. Dynamic truncation length: If you want to truncate the length to be configurable instead of hardcoded, you can define it as a variable. For example, use it at the top of the template{% set max_length = 20 %}, and then use it in the filter{{ item.Title|truncatechars:max_length }}.

  2. Category name contains HTML tagsIf your category name(item.Title) occasionally contains HTML tags (such as for bold or highlighting), use them directly.truncatecharsMay damage the HTML structure, causing the page to display abnormally. At this time, Anqi CMS providestruncatechars_htmlFilter. This filter will intelligently parse HTML, maintaining the integrity of the tag structure during truncation, and avoiding page errors.

    {# 如果分类名称中可能包含HTML,则使用 truncatechars_html #}
    {{ item.Title|truncatechars_html:20 }}
    
  3. Word truncationIn some languages (such as English), truncating by character may cause words to be cut off. If you prefer to maintain the integrity of the word, you can usetruncatewordsA filter. It truncates by word count and adds an ellipsis after the last complete word. Similarly, there is alsotruncatewords_htmlUsed to process strings with HTML.

    {# 按单词截断,适用于需要保持单词完整性的场景 #}
    {{ item.Title|truncatewords:5 }}
    

Summary

Bytruncatecharsor its variants (truncatechars_html,truncatewords,truncatewords_html) And the strong filters built into AnQi CMS, we can easily manage the display length of dynamic content in templates.This is not only a small trick to enhance the beauty of the website, but also an important link to optimize the user experience and ensure the effectiveness of responsive design.Remember, details determine success or failure. A tidy and organized website always leaves a better impression on users.


Frequently Asked Questions (FAQ)

Q1: Why should category names be truncated? Isn't it okay to display the full name?A1: Truncating category names is mainly to enhance user experience and page aesthetics.Long names in navigation bars, lists, or widgets can cause layout confusion, text overflow, and disrupt the排版 balance, especially on mobile devices, the problem is more prominent.Truncate and add an ellipsis to maintain interface neatness, ensure visual consistency, and simultaneously pass throughtitleThe attribute (hover tip) provides complete information, balancing beauty and information integrity.

Q2:truncatecharsCan the ellipsis (...) added by the filter be customized? For example, can it be changed to...[更多]?A2:truncatecharsThe ellipsis built into the filter is fixed...It cannot be modified directly through the filter parameters. If you need to customize the ellipsis style or content, you need to combinelengthFilter and conditional judgment to be implemented manually. For example, first judgeitem.TitleThe actual length is whether it exceeds the expected, if it exceeds, then manually truncate the string and concatenate the custom ellipsis. This will increase the complexity of the template, usually in the default...Sufficient to meet the needs.

Q3: If my category name is multilingual, how should I set the truncation length?A3: For multilingual websites, the setting of truncation length needs to be more cautious.The character width and information density of different languages (such as Chinese, English, Japanese, etc.) vary greatly.For example, a Chinese character usually contains more information than an English character.Therefore, to ensure good display effects in all languages, you may need to:

  1. Adjust truncation length based on language.In multilingual templates, values can be dynamically set based on the current language environment (throughsystemtag to obtainLanguageinformationtruncatecharslength parameters.
  2. Prioritize visual effects: As per the actual display effect, perform more tests to find a balance point acceptable in all target languages.
  3. Usetruncatewords: For languages like English that are unit-based on words,truncatewordsmay be more thantruncatecharsIt is more suitable because it does not truncate words, avoiding reading difficulties.

Related articles

`categoryList` returns the category data whether it includes user group or permission-related setting information?

In the daily operation and template development of AnQi CMS, we often need to obtain site data from different angles, and the category list (`categoryList`) is undoubtedly one of the most commonly used tags.However, regarding whether the `categoryList` returned classification data includes user group or permission-related setting information?This topic, we delve into the design philosophy and functional implementation of AnqiCMS, revealing the logic behind it.

2025-11-06

How to handle the pagination problem when nesting `archiveList` inside `categoryList`?

As an experienced website operations expert, I have accumulated rich experience in the content management practice of AnQiCMS.I am well aware that when facing the powerful template tag system of AnQiCMS, how to skillfully combine them to achieve the expected content display effect is a challenge that many operators and developers will encounter.Today, let's delve into a common yet confusing issue: how to properly handle the pagination problem of `archiveList` when nesting `categoryList`?

2025-11-06

Is the HTML structure generated by `categoryList` friendly to search engine crawlers, and how can it be optimized?

As an experienced website operations expert, I know that every detail can affect the performance of a website in search engines.Today, let's delve deeply into the `categoryList` tag generated by AnQiCMS, the degree of friendliness of its HTML structure to search engine spiders, and how we can cleverly optimize it to improve the website's SEO performance.Since its inception, AnQi CMS has been favored by operators for its SEO-friendly design concept.

2025-11-06

How to extend the additional features of the `categoryList` tag without modifying the AnQiCMS core code?

As an experienced website operations expert, I fully understand how to skillfully utilize the existing functions of the CMS system to expand without touching the core code, which is crucial for maintaining system stability and reducing upgrade costs.AnQiCMS (AnQiCMS) offers us a powerful tool for deep customization at the content operation level with its flexible template engine and rich tag system, among which the `categoryList` tag is often a point where we need to expand the function.In Anqi CMS

2025-11-06

How to use the AnQiCMS `commentList` tag to display comments on the frontend page?

As an experienced website operations expert, I know that an active website cannot do without user interaction, and the comment feature is an important embodiment of user participation.In AnQiCMS (AnQiCMS), integrating and displaying comments is not difficult.Today, let's delve deep into how to use the powerful `commentList` tag of AnQiCMS to elegantly present comment content on your website's frontend page, thereby enhancing user engagement and content vitality.

2025-11-06

In AnQiCMS, how can the `commentList` tag implement pagination for comment data?

As an experienced website operations expert, I am well aware that the comment function in a content management system not only increases user interaction but also brings vitality and richness to the website.AnQiCMS (AnQiCMS) is an efficient content management system developed based on the Go language, which provides strong comment functions while also considering the flexibility of template creation.Today, let's delve into how to elegantly implement pagination of comment data using the `commentList` tag in AnQiCMS.--- ### AnQiCMS in English

2025-11-06

How to configure the `commentList` tag to display comments for a specific article (`archiveId`)?

I am glad to analyze the comment management and template configuration skills of Anqi CMS for you in depth.In website content operation, comments are an important bridge connecting users to content.AnQiCMS as an efficient content management system naturally also provides powerful comment functions and flexible template tags, helping us accurately control the display of comments. Today, we will focus on a common and core requirement: **How to configure the `commentList` tag to display comments for specific articles (`archiveId`) only?

2025-11-06

What sorting methods does the AnQiCMS comment list support (`order` parameter), and how to sort by the latest or the most popular?

As an experienced website operations expert, I am well aware of the importance of user interaction in content management.The comment feature is an important indicator of website activity, and how efficiently and friendly these comments are displayed directly affects user experience and the spread of content.AnQiCMS as a powerful content management system also provides flexible configuration options for comment management.Today, let's delve into the sorting method of AnQiCMS comment list, especially how to display comments based on the latest release or popularity.--- ##

2025-11-06