How to automatically wrap long text to a specified length in AnQiCMS template?

Calendar 👁️ 68

In the presentation of website content, the display method of long text is often a key factor affecting user experience and page aesthetics.When we need to display a long text content, such as an article summary, product description, or detailed introduction, in a more readable and layout-adaptive way, AnQiCMS' template function provides a powerful and flexible solution.

AnQiCMS uses a syntax similar to Django's template engine, with built-in filters (Filters) that can help us easily implement text formatting, including how to automatically wrap long text to a specified length.

AnQiCMS's solution:wordwrapFilter

In order to implement automatic line wrapping for long text in the AnQiCMS template, we can utilizewordwrapFilter. This filter can insert line breaks between words in text based on the specified character length, (\nThis allows for 'soft wrapping' of text. This means it does not force a word to be cut off, but rather wraps at word boundaries to ensure the natural flow of text.

wordwrapBasic usage of filters:

wordwrapThe filter accepts a numeric parameter indicating the maximum number of characters per line. For example, if you want to display a maximum of 20 characters per line, you can use it like this:

{% set longText %}{% lorem 50 w %}{% endset %} {# 使用lorem标签生成一段长文本作为示例 #}

<h3>原始文本:</h3>
<p>{{ longText }}</p>

<h3>指定20个字符换行后:</h3>
<pre>{{ longText|wordwrap:20 }}</pre>

In the above example,{% lorem 50 w %}Used to generate a random Latin text containing 50 words for demonstration purposes.longText|wordwrap:20This indicates that the text will be wrapped at a maximum of 20 characters per line. To make the wrapping effect more intuitive, we placed the processed text inside the<pre>tags becausepreThe label will retain the original line breaks and spaces in the text.

Why choosewordwrap?

wordwrapThe advantage of the filter is that it can maintain the semantic integrity of the text.It looks for spaces between words as line breaks, which avoids splitting a word in the middle and is crucial for improving readability.For example, when displaying a list of product features, if each feature description is too long, usewordwrapThey can be elegantly folded without breaking the word structure to fit the width of the list items.

Deep understandingwordwrapPrinciples and注意事项

wordwrapThe filter mainly relies on spaces in the text to determine the line break points. This means that if there is a long string of continuous characters without any spaces in your text (for example, in Chinese, Japanese, Korean, etc., languages that do not have natural word separators),wordwrapIt will not be possible to break lines within this long string. In this case, the browser may treat it as an indivisible 'word' and may cause text overflow within the container.

Therefore, when usingwordwrapWhen, especially when dealing with CJK (Chinese, Japanese, Korean) text, please note its characteristics. For scenarios that require forced line breaks at any character position, it may be necessary to combine with front-end CSS styles (such asword-break: break-all;oroverflow-wrap: break-word;Ensure compatibility in extreme layout situations.

Related but different text processing methods.

exceptwordwrapIn addition to "auto-wrap", AnQiCMS also provides other practical text processing filters, which are different in function although they are related to text length.

  1. truncatecharsandtruncatewordsText truncated and ellipsis addedIf you need to shorten long text to a specified length and add an ellipsis at the end (...ThentruncatecharsTruncated by character count andtruncatewords(Truncated by word count) is a more suitable choice. They are often used to display article summaries, ensuring that the content does not occupy too much space.

    • Example (truncatechars):

      {% set articleSummary = "这是一篇很长的文章摘要,我们希望它能够在一个固定长度内显示,并且在末尾加上省略号以示内容未完。" %}
      <p>{{ articleSummary|truncatechars:20 }}</p> {# 输出:"这是一篇很长的文章摘..." #}
      
    • Example (truncatewords):

      {% set articleSummaryEn = "This is a very long article summary that we want to display within a fixed length with ellipses." %}
      <p>{{ articleSummaryEn|truncatewords:8 }}</p> {# 输出:"This is a very long article summary that..." #}
      
  2. linebreaksandlinebreaksbr: Handle existing newline charactersThese filters are used to convert existing line breaks in text (\n) to HTML tags or using<br/>}<p>Label wrapping. They do not automatically insert line breaks based on length, but rather process the line breaks explicitly present in the source text. This is very useful for displaying user input text with segments.

    • Example (linebreaksbr):
      
      {% set userContent = "用户输入的第一段内容。\n这是第二段内容,中间有换行符。" %}
      <p>{{ userContent|linebreaksbr|safe }}</p> {# 将\n转换为<br/> #}
      

Examples of actual application scenarios

  • Summary display on the article list page:You can usetruncatecharsortruncatewordsTo control the length of the summary, keep the page tidy.
  • Key parameters on the product details page:If the value of a product parameter is too long, consider usingwordwrapBreak at the appropriate position to fit the layout and avoid overflow.
  • Descriptive text in the sidebar or widget:These areas have limited space,wordwraportruncatecharsHelp you elegantly display information.

Mastering these text processing filters will give you greater control over content presentation in the AnQiCMS template, thereby creating websites that are more attractive and align with user expectations. By using them flexiblywordwrap/truncatecharsFilters like this, you can ensure that the website provides a **reading experience** on different devices and layouts.


Frequently Asked Questions (FAQ)

Q1: WhywordwrapDoes the filter not work on Chinese text?A1: wordwrapThe filter mainly inserts line breaks by identifying spaces in the text

Related articles

How to safely output HTML code in the template without escaping in AnQiCMS?

When using AnQiCMS for website template development or content display, you may encounter situations where you need to output HTML code directly on the page, only to find that the code is automatically escaped, for example, the `<p>` tag becomes `&lt;This often confuses those who are new to it.In fact, this is the default measure taken by the AnQiCMS template engine for website security.### Understanding the default security mechanism of AnQiCMS templates The AnQiCMS template engine design has drawn inspiration from

2025-11-08

How to truncate a string and add an ellipsis (...) to limit the display length in AnQiCMS template?

In AnQiCMS template development, we often need to refine the content displayed on the website, such as article titles, summaries, or abstracts of a text.If the content is too long, it not only affects the beauty of the page, but may also reduce the user's reading experience.AnQiCMS's powerful template engine provides a simple and efficient method to solve this problem, allowing us to easily extract strings and automatically add ellipses (...) to elegantly limit the display length of content.

2025-11-08

How to format a timestamp (timestamp) into a readable date format for display in AnQiCMS?

In the process of website operation, the effective display time of content publishing or updating is crucial for improving user experience and the readability of content.If time information is presented in the original timestamp format, it is often difficult for ordinary users to understand.AnQiCMS provides a straightforward and flexible way to help you convert these digital timestamps into easily readable date and time formats.### How AnQiCMS handles timestamps AnQiCMS typically uses standard Unix Timestamp format for storing content time information

2025-11-08

How to use a `for` loop to iterate over data and display content in AnQiCMS templates?

In AnQiCMS template development, we often need to display a series of dynamic content, such as the latest article list, product categories, navigation menu items, and even custom parameters.At this point, the 'for loop' has become the core tool for us to traverse these data and display it on the web page.Understand and master the `for` loop, which will greatly enhance the flexibility and development efficiency of the template.### Core Grammar: The Foundation of Data Traversal The `for` loop syntax in AnQiCMS templates is concise and intuitive, borrowing the style of the Django template engine.

2025-11-08

How to automatically parse a URL string into a clickable HTML link in AnQiCMS template?

In AnQiCMS template development, we often encounter the need: the URL string contained in the content should be automatically converted into a clickable HTML link to enhance user experience and page interactivity.Manually adding links is undoubtedly cumbersome and unrealistic, fortunately AnQiCMS provides powerful template filters that can help us easily achieve this function.AnQiCMS template engine supports Django-like syntax, which includes a series of practical filters that can process variable content.For automatic parsing of URL strings

2025-11-08

How to define and use temporary variables in AnQiCMS templates to simplify content display?

When developing templates in AnQiCMS, we often encounter situations where we need to process some complex data or reuse a certain calculation result.To make the template code more concise, readable, and maintainable, AnQiCMS provides a powerful mechanism for defining and using temporary variables, mainly through the `with` and `set` tags.Reasonably utilizing them can greatly enhance our content display efficiency and flexibility. ### Simplified Content Display: Why do we need temporary variables?

2025-11-08

How to implement the link display for multi-language site switching in AnQiCMS?

In today's globalized digital world, multilingual support for websites has become crucial for reaching a wider audience and expanding market boundaries.AnQiCMS (AnQiCMS) fully understands this need, therefore, it takes multilingual support as one of its core features, aiming to help users efficiently build and manage multilingual websites.This article will focus on how to implement the display of language switch links for multi-language sites in AnQiCMS, supplemented by necessary SEO practices, and provide you with a comprehensive guide.

2025-11-08

How to add `hreflang` tags in AnQiCMS template for multilingual pages to optimize SEO?

In today's globalized internet environment, many websites need to provide content for audiences of different languages or regions.To ensure that these multilingual pages can be correctly understood and displayed by search engines, the `hreflang` tag plays a crucial role.It can tell search engines that your website has multiple language versions and which version should be displayed to which user.

2025-11-08