In modern web design, the flexibility of content display is crucial, especially for core elements like article titles.How to elegantly truncate the title when it is too long and the layout space is limited, so that it maintains readability and adapts to different devices and layouts, which is a common problem encountered in AnQiCMS template development.Fortunately, AnQiCMS's powerful template engine provides a simple and efficient solution.

The challenge of title truncation and the advantage of word-by-word truncation

AnQiCMS template engine supports a variety of content filters (Filters), including those specifically designed for content truncationtruncatewordsA filter that can truncate by word, ensuring that the truncated title is semantically complete, greatly enhancing the user experience.

UsetruncatewordsFilter implementation for word truncation

In AnQiCMS template, we usually get the article title byarchiveListlooping through tagsitem.Title, or directly using it on the article detail pagearchive.Title. To implement word truncation, just simply add it to the variable of the title plus|truncatewords:Nand it represents the number of words you want to keep.N.

For example, if you want a title to display a maximum of 8 words and automatically add an ellipsis at the end, you can write it like this:

{{ item.Title|truncatewords:8 }}

Assuming the original title is: "How to truncate article titles by word and display an ellipsis to adapt to different layouts in AnQiCMS templates?"

If using{{ item.Title|truncatewords:8 }}The result will be: "How to truncate article titles by words and display them in AnQiCMS templates"

You will find that truncation occurs after the word "display", not in the middle, and the ellipsis is also automatically added, making it more natural and smooth than simple character truncation.

Handle titles that may contain HTML tags

Although the title of the article is usually plain text, in some special cases, the title may contain some simple HTML tags, such as to emphasize a word, it may use<strong>Tags. If we use it directly at this timetruncatewordsThese HTML tags may be incorrectly truncated, causing the page rendering to be abnormal.

For this situation, AnQiCMS providestruncatewords_htmlFilter. It istruncatewordsSimilar, but capable of intelligently recognizing and preserving the integrity of HTML tags, ensuring that the truncated HTML structure remains valid. When usingtruncatewords_htmlit is usually necessary to coordinate with|safeA filter that tells the template engine that this content is safe HTML and does not require additional escaping.

{# 假设 item.Title 包含 HTML 标签,例如 "在AnQiCMS模板中,<strong>重要</strong>标题截断" #}
{{ item.Title|truncatewords_html:8|safe }}

This can be correctly truncated and safely displayed even if the title contains HTML.

Apply title truncation in the actual article list

The most common application scenario is on the article list page.Imagine, an article list may take up an entire row on the PC, but is cramped into a narrow card on the mobile.truncatewordsThe number of words, we can easily deal with.

Here is a simple article list template snippet, showing how to truncate article titles in a loop:

<div class="article-list">
    {% archiveList archives with type="list" limit="10" %}
        {% for item in archives %}
        <div class="article-item">
            <a href="{{ item.Link }}" class="article-link">
                <h3 class="article-title">
                    {# 在这里对标题按词截断,例如显示10个单词 #}
                    {{ item.Title|truncatewords:10 }}
                </h3>
                <p class="article-description">
                    {# 描述也可以同样处理,例如显示20个单词 #}
                    {{ item.Description|truncatewords:20 }}
                </p>
                <span class="read-more">阅读更多</span>
            </a>
        </div>
        {% empty %}
        <p class="no-content">暂无相关文章。</p>
        {% endfor %}
    {% endarchiveList %}
</div>

In a real project, you can set different word truncation quantities according to different layout areas.For example, the recommended area on the homepage may only need 5 words, the category list page can have 10 words, and the related article area may return to 5 words.

Practical tips

  • Choose an appropriate truncation length:There is no such thing as a permanent number.You need to test at different device positions, text sizes, and expected line counts based on the design draft to find a word count that can ensure information delivery without disrupting the layout.
  • Combined with CSStext-overflow:ThoughtruncatewordsOn the Go template level, it provides the function of truncating by word and adding an ellipsis, but if you want the title to be displayed on one line and the truncation to be at the character level (for example, the word is broken in the middle), and the ellipsis is controlled at the CSS level, you can also combine CSS.text-overflow: ellipsis; white-space: nowrap; overflow: hidden;Property. This is usually applicable when there is a strict requirement for truncation of single-line characters and it is not a problem if words are cut off. For truncation that seeks readability and semantic completeness, truncatewordsIs a better choice.
  • Maintain consistency:Keep the title truncation logic consistent on the same page or in the same layout to avoid confusing the user visually.

AnQiCMS's template engine, with its powerful filtering features, allows us to easily implement word truncation of article titles and flexibly adapt to the ever-changing website layout, thus finding a perfect balance between content presentation and user experience.


Frequently Asked Questions (FAQ)

1.truncatecharsandtruncatewordsWhat are the differences between the filters? Which one should I choose?

truncatecharsThe filter is truncated by character count, regardless of whether the characters form a complete word. For example,"AnQiCMS教程"|truncatechars:5It may output"AnQiC..."HowevertruncatewordsThe filter truncates by word count, ensuring that the last word of the truncation is complete. For example,"AnQiCMS教程大全"|truncatewords:2It will output."AnQiCMS教程...".

Choose which one depends on your specific needs. If you have a high requirement for the semantic integrity of the title, or want to avoid words being cut in half, thentruncatewordsIs a better choice. If you simply limit the total number of characters and do not mind the words being cut off, you can usetruncatechars.

2. How to customize the ellipsis style, or replace the default “…” with other symbols?

Built-in in AnQiCMStruncatewordsandtruncatecharsThe filter automatically adds "..." as an ellipsis when truncating, and this symbol is currently fixed. If you need to customize the ellipsis style or replace the symbol, you may need more complex logic: First, you need to usesetLabel a variable to store the truncated content (without ellipsis), then compare the length of the original title and the truncated content. If the original title is longer, manually concatenate your custom ellipsis. For example:

{% set original_title = item.Title %}
{% set truncated_content = original_title|truncatewords:5 %}
<h3 class="article-title">
    {% if original_title|length > truncated_content|length %}
        {{ truncated_content|cut:"..." }}... [查看更多]
    {% else %}
        {{ original_title }}
    {% endif %}
</h3>

(Please note: the abovetruncated_content|cut:"..."is to remove the ellipsis that comes with the filter so that it can be added manually. In fact,truncatewordsWhen not truncated, an ellipsis is not added, so a simpler judgment is to directly compare the length.) A more concise logic is:

{% set title_limit = 5 %}
{% set displayed_title = item.Title|truncatewords:title_limit %}
<h3 class="article-title">
    {{ displayed_title }}
    {% if item.Title|length > displayed_title|length and displayed_title|slice:"-3:" != "..." %}
        ... [查看更多] {# 这里的判断是为了确保只有在真正截断且过滤器未添加省略号时才追加,但AnQiCMS过滤器默认会加,所以这个判断主要用于自定义末尾文本 #}
    {% endif %}
</h3>

But in most cases, the default filter is:...It can meet most needs already.

3. In some specific layouts, I want the title to be displayed on one line, even if it is truncated by word, it may not be enough, what should I do?

When you need to display the title strictly as a single line, even if the text is truncated by words, if the number of words still causes the text to overflow, you may need to combine CSS to handle it. A common practice is to: first usetruncatewords(Or other truncation methods) roughly control the text length, then apply CSS styles to the title element:

.article-title {
    white-space: nowrap; /* 防止文本换行 */
    overflow: hidden;    /* 隐藏溢出内容 */
    text-overflow: ellipsis; /* 在溢出处显示省略号 */
}

This CSS method will force the text to be displayed on one line: