How does the `wordwrap` filter automatically wrap long text to a specified length

Calendar 👁️ 75

In the daily operation of websites, we often encounter such situations: the article content is too long, or the text extracted from other places has not been formatted, resulting in the text content exceeding the container width when displayed on the web page, destroying the overall layout and seriously affecting the user's reading experience.Especially on mobile devices, long lines of text are more difficult to read.In order to solve this problem, AnQi CMS provided a very practical tool -wordwrapFilter, it can help us automatically wrap long text according to a specified length, thereby optimizing the display effect of the content.

What iswordwrapFilter?

wordwrapThe filter is a built-in feature of Anqi CMS template engine, which mainly serves to 'intelligently' break a long text content into lines according to the maximum length you set.The 'smart' aspect is that it tries to break lines between words to maintain the integrity of words, avoiding cutting a word in half, thereby ensuring the readability of the content.

Why is it neededwordwrapFilter?

UsewordwrapFilter, not only can make your website content look neater, but also bring a variety of operational advantages:

  1. Improve reading experience: Long lines of text increase the difficulty of reading for users, and the eyes need to move back and forth frequently. By using automatic line breaks, the length of each line of text can be moderate, reducing reading fatigue.
  2. Optimize page layoutThe text content no longer arbitrarily fills the container, you can more accurately control the width of the element, ensuring that the page maintains the expected beautiful layout on different devices and screen sizes.
  3. Enhance responsive performanceOn mobile and other small-screen devices,wordwrapcan better adapt to limited display space, allowing content to be presented-friendly across different terminals.
  4. Improve SEO friendliness: Although not a direct SEO factor, good user experience (UX) will indirectly affect user stay time, bounce rate, and other indicators, which are all references for search engines to evaluate the quality of a website.

wordwrapHow to use the filter

Using in Anqi CMS template,wordwrapThe filter is very simple and intuitive. Its basic syntax is:

{{ obj|wordwrap:长度数字 }}

Here:

  • objRepresents the text content you need to process, it can be a variable, a string, or any data that can be interpreted as text.
  • 长度数字Is an integer representing the maximum number of characters you want per line.wordwrapWill attempt to wrap text based on this number.

For example, if you have a long English description and you want to display no more than 20 English characters (words) per line, you can write it like this:

{{ "This is a very long sentence that needs to be wrapped for better readability on your website."|wordwrap:20 }}

This code's output will be something like this:

This is a very long
sentence that needs
to be wrapped for
better readability
on your website.

You can see that the filter tries to wrap at spaces to ensure the integrity of the word.

Practical application and precautions

wordwrapThe filter is very flexible in practical applications, but some details need to be paid attention to:

  1. The difference in handling Chinese and English textThis is usingwordwrapa very important note to pay attention to.wordwrapThe filter mainly relies on "spaces" to identify words and perform line breaks.

    • English text: As English words have natural spaces between them,wordwrapThe effect is usually very ideal, it will break the words between them, maintaining the integrity of semantics.
    • Chinese text: There are no spaces between Chinese characters. Therefore, if a segment of Chinese is continuous,wordwrapIt will consider it a very long "word". In this case, unless the text contains spaces or punctuation, thenwordwrapCannot automatically wrap between Chinese characters. If you need to force a line break for Chinese at a specified length (even if it truncates Chinese characters), you may need to combine it with frontend CSS styles (such asword-break: break-all;To implement, but this goes beyondwordwrapthe scope of the filter function.
  2. CombinelinebreaksbrFilterIf the original text itself contains newline characters(\n)wordwrapit will respect these existing newlines. However, in HTML,\nIt will not automatically render as a visible newline. If you want these newline characters to also be displayed on the page as<br>you can use the tag in conjunction withlinebreaksbrThe filter is used:

    {{ content|wordwrap:50|linebreaksbr|safe }}
    

    This code will first convertcontentTranslate 50-character (English word) length, then all\nto<br>.

  3. UsesafeFilter HTML contentWhen the text content you are processing may contain HTML tags, in order to avoid HTML tags being escaped into plain text (for example<p>becomes&lt;p&gt;), you shouldwordwrapimmediately after usingsafeFilter:

    {{ archive.Description|wordwrap:80|safe }}
    

    This ensures that HTML tags in the text arewordwrapstill able to be correctly parsed and rendered by the browser.

  4. In<pre>displayed accurately in the tagsFor code blocks, poetry, or any text that needs to be preserved in its exact format,wordwrapcombined with HTML's<pre>tags can provide excellent display effects.<pre>tags will preserve the spaces and line breaks in the text.

    <pre>{% filter wordwrap:15 %}{% lorem 30 w %}{% endfilter %}</pre>
    

    This code will generate 30 random words, then break every 15 words into a new line, and ensure that it is displayed precisely in a pre-formatted style on the page.

Example display

Let us experience some specific exampleswordwrapThe effect of the filter:

1. Basic applicationSplit a long English text into lines of 10 words:

{{ "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."|wordwrap:10 }}

Output effect:

Lorem ipsum dolor
sit amet, consectetur
adipiscing elit. Sed
do eiusmod tempor
incididunt ut labore
et dolore magna
aliqua.

2. Combinedloremand<pre>TagUseloremTags generate random text, and throughwordwrapControl line break and then use<pre>Keep the format of tags:

<pre>{% filter wordwrap:15 %}{% lorem 20 w %}{% endfilter %}</pre>

Output effect:

<pre>Lorem ipsum dolor
sit amet, consectetur
adipisici elit, sed
eiusmod tempor incidunt
ut labore et dolore
magna aliqua.</pre>

3. Process text with line breaks and HTML tagsAssumearticleContentContains the following content:这是第一段。<br>第二段内容很长,需要换行处理。

{{ articleContent|wordwrap:20|safe }}

IfarticleContentThe actual text is这是第一段。第二段内容很长,需要换行处理。and there is no actual<br>label, then the output will be:

这是第一段。第二段内容
很长,需要换行处理。

Note that because it is Chinese, it does not wrap within Chinese characters, until it encounters a period or other space symbol.

Summary

wordwrapThe filter is a small tool in Anqi CMS template that can greatly enhance user experience.It can help you easily solve the problem of long text not displaying well on the page, making your website content more readable and beautiful.Understand its working principle, especially the differences in Chinese and English text processing, and make good use of collocationslinebreaksbrandsafeOther filters will make your content operation on Anqi CMS twice as effective.


Frequently Asked Questions (FAQ)

1.wordwrapCan the filter handle automatic line breaks for Chinese text? wordwrapThe filter mainly determines the line break point by identifying spaces. For Chinese text, as there are usually no spaces between Chinese characters, it treats consecutive characters as a single long 'word', so it cannot implement automatic line breaks between Chinese characters by default.It will only find spaces or punctuation marks in the text to perform line breaks.

Related articles

How to calculate the number of words in a string with the `wordcount` filter in Anqi CMS template?

When processing text content in the AnQi CMS template, we often need to perform various operations on strings, such as counting words, cutting content, and so on.Among them, calculating the number of words in a string is a common requirement, which is very useful in content analysis, SEO optimization, and even estimating the reading time of an article.AnQi CMS provides a simple and powerful tool——`wordcount` filter.### `wordcount` filter: Core functionality and purpose The `wordcount` filter is specifically used to count the number of words in a given string

2025-11-08

How `urlize` and `urlizetrunc` filters automatically convert URLs and email addresses in text to clickable hyperlinks?

How to efficiently and beautifully convert text containing URLs and email addresses into clickable hyperlinks when managing website content in AnQi CMS, is a concern for many content operators.Manually adding the `<a>` tag to each URL or email is not only time-consuming and labor-intensive but also prone to errors.Luckily, AnQi CMS provides two very practical template filters——`urlize` and `urlizetrunc`, which can automatically complete this task and greatly improve the efficiency and user experience of content publishing.### `urlize`

2025-11-08

What are the differences between the `urlencode` and `iriencode` filters in URL parameter encoding, and which scenarios are they applicable to?

In website operation, the construction and processing of URL (Uniform Resource Locator) is a fundamental and critical task.It is crucial to properly encode URLs when dynamically generating links, handling user input as parameters, as it ensures the validity of the links, prevents garbled text, and potential security issues.AnQiCMS provides the `urlencode` and `iriencode` filters to help us better manage special characters in URLs.Although they are all used for encoding, their application scenarios and processing methods are different.

2025-11-08

How to safely truncate text with HTML tags using `truncatechars_html` and `truncatewords_html` filters to prevent structure damage?

In website content operation, we often need to display the summary or part of the content in different scenarios, such as on the list page, search results, or related recommendations.This is when you need to truncate the content.If the content is plain text, a simple character or word cutter can handle the task well.However, when the content is rich in HTML tags, the problem becomes complex: directly cutting may cause the HTML tags to be truncated, thereby destroying the page structure, causing display errors, and even affecting the user experience.

2025-11-08

How does AnQiCMS ensure that website content displays perfectly on different devices?

In the digital age, website content can seamlessly adapt to various devices, from large desktop monitors to small smartphone screens, and is no longer an option, but the cornerstone of success.The user expects to have a smooth, beautiful, and fully functional experience regardless of which device is accessed.AnQiCMS as a product designed for efficient content management, provides a series of powerful and flexible features to ensure that your website displays content perfectly on any screen, making it shine on any screen.### AnQiCMS's multi-dimensional adaptive strategy AnQiCMS

2025-11-08

How to manage and present the content of multiple independent brand websites in AnQiCMS in a unified manner?

In the current digital age, the need for enterprises or content operators to manage multiple independent brand websites is increasingly common.Each brand may have a unique style, product line, or target audience, but how to efficiently manage these contents under a unified framework, achieve centralized display under specific scenarios, while maintaining the independence of each brand, is a challenge faced by many teams.AnQiCMS as an enterprise-level content management system, its multi-site management function provides a powerful solution for this.One of the design初衷 of AnQiCMS is to serve users with multi-site management needs

2025-11-08

How to flexibly display different content types on the front-end page after customizing the content model?

In modern website operations, the diversity and personalized display of content is the key to attracting users and enhancing brand image.AnQiCMS (AnQiCMS) with its flexible content model design, brings unprecedented freedom to website content management.How to elegantly present the content with unique structure on the front page after we customize the content model according to business requirements, is a core skill that every operator needs to master.

2025-11-08

How to implement the language support feature of AnQiCMS for content switching and correct display?

## Unlock Global Audience: How AnQiCMS Achieves Multi-language Content Switching and Accurate Display Under the wave of globalization, websites are no longer aimed at users in a single region.Whether it is to expand the international market, serve diverse cultural groups, or enhance brand influence, multilingual support has become an indispensable ability for modern websites.AnQiCMS as an efficient content management system, deeply understands this, and provides a flexible and practical multilingual solution to help users easily switch and display content in different language versions. AnQiCMS

2025-11-08