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.