How to implement automatic line break display for long text?

Calendar 👁️ 85

In website content operations, we often encounter situations where a large amount of text needs to be displayed. If these long texts are not properly handled, they may exceed the designed container, causing page layout to become disordered and severely affecting user experience.Anqi CMS provides us with flexible and powerful template functions, which can easily solve the display problems of long text, especially for automatic line breaks.

Core strategy: utilizingwordwrapFilter implementation for text automatic line break

The AnQi CMS template system is built-in with many practical filters (Filters), among whichwordwrapThe filter is specifically used to handle long text automatic line breaks.Its function is to wrap a long text according to the character length we set.When a line of text reaches a specified length,wordwrapThe filter tries to break lines at the start of the next word to maintain the integrity of the word.

UsewordwrapThe filter is very intuitive, you usually call it like this in the template:

{{ 您的长文本变量 | wordwrap: 每行字符数 }}

For example, if you want to make a long text namedarchive.Contentwrap automatically at about 50 characters per line

<div class="content-display">
    {{ archive.Content | wordwrap:50 | safe }}
</div>

In this example,archive.Contentit is the article content you edit in the Anqi CMS background.wordwrap:50The text content is wrapped every approximately 50 characters.

It should be noted particularly that,wordwrapThe filter is based onwordsIt performs line breaks, it finds spaces in the text to determine the break points.This means that if your content is a string of continuous characters without spaces (such as a long English URL or a large block of continuous Chinese text), it will not automatically break in the middle and may extend beyond the container.

To avoid HTML tags contained in the content (such as<strong>/<a>It is treated as ordinary text on the front end and not parsed by the browser, you need to usewordwrapafter the filter is usedsafefilter.safeThe filter tells the template engine that this content is safe and does not need to be escaped as HTML entities. It can be output directly as HTML code.

Other related filters: truncation and line break options

exceptwordwrapUsed for automatic line breaks, Anqi CMS also provides some other filters, which although they also play a role in "shortening" or "formatting" long text, their purpose andwordwrapDifferent. Understanding these differences will help you choose the most suitable tool.

  1. truncatecharsandtruncatewordsText truncated:These filters are used to truncate text instead of wrapping. They will cut off the extra text after reaching the specified length and add an ellipsis at the end (...)

    • truncatechars:N: Truncate by character count, including an ellipsis.
    • truncatewords:N: Truncate by word count, including an ellipsis. These filters are very useful when your page only needs to display an article summary or limit the absolute length of text.If your text contains HTML tags, in order to avoid the structure being destroyed after truncation, please use their corresponding HTML safe versions: truncatechars_html:Nandtruncatewords_html:N.

    For example:

    <p>{{ archive.Description | truncatechars:100 | safe }}</p>
    

    This code will truncate the article summary to 100 characters and add an ellipsis at the end.

  2. linebreaksandlinebreaksbr: Convert newline characters to HTML tags.If your long text in Anqi CMS background editing has already included line breaks (such as paragraphs created by content editors through the Enter key), and you want these line breaks to be converted to HTML on the front end,<br>tags or<p>Tags, then you can use these two filters.

    • linebreaks: Converts line breaks to HTML.<p>Tags, and adds them when there are blank lines.<br>.
    • linebreaksbr: Simply converts all line breaks to HTML.<br>Label. These filters mainly handle the existing line breaks in the text source, rather thanwordwraplike automatically generating line breaks based on display width.

    For example:

    <div class="formatted-text">
        {{ category.Content | linebreaks | safe }}
    </div>
    

    This will convert line breaks in category content to paragraphs or line break tags.

Strategies and considerations in practice**

To implement the elegant display of long text, it is usually necessary to combine the template filter of Anqicms with the front-end CSS style.

  1. CSS line break aid:For long URLs, long strings of numbers, or Chinese text without spaces, etc.,wordwrapThe filter may not break in the middle. In this case, you can use CSS to force the browser to break words and wrap lines. Add the following to the container in your CSS:

    .content-display {
        word-wrap: break-word; /* 兼容旧浏览器 */
        overflow-wrap: break-word; /* 现代浏览器 */
    }
    

    This will allow the browser to wrap words within a word, even without spaces.

  2. Content editing specification:Encourage content editors to use paragraphs and line breaks reasonably when writing long texts, especially to appropriately insert spaces between Chinese paragraphs, which helpswordwrapthe filter work better.

  3. Multi-platform test:The website content will be displayed on various devices including PC, tablet, and smartphone.There is a significant difference in screen width among different devices, therefore, it is necessary to test the display effect of long text on different devices and browsers before publishing, to ensure that it can automatically wrap gracefully in all scenarios and maintain a beautiful layout.

By flexibly using AnQi CMS'swordwrapFilters and other related tools, combined with appropriate CSS styles, will allow you to easily handle long text display on the website, providing users with a smooth and professional reading experience.

Frequently Asked Questions (FAQ)

Q1: I usedwordwrapthe filter, but the long Chinese or English URL does not automatically wrap, what is the matter?A1: wordwrapThe filter mainly breaks lines based on spaces in the text. If your Chinese text is continuous without spaces, or if the English URL is a long string without spaces,wordwrapCannot find a suitable breakpoint. In this case, you need to use CSS styles to assist.word-wrap: break-word;oroverflow-wrap: break-word;Apply to the HTML element containing text, which will force the browser to break words at any character to fit the container width.

Q2: When should it be used?wordwrapFilter, when should it be usedtruncatecharsortruncatewordsFilter?A2: It depends on your display needs.

  • If you want the long text to be displayed completely inside the container, you should usewordwrapfilter.
  • If you only need to display a part of the text, such as an article summary, and add an ellipsis at the end to indicate that the content is incomplete, then you should usetruncatechars(truncated by character count) ortruncatewords(Truncated by word count).

Q3: The content of my article is edited by a rich text editor, which includes HTML tags and useswordwrapAfter the filter, why did the HTML tags appear directly on the page instead of the style?A3: This is because the Anqi CMS template system defaults to escaping all output content with HTML entities to prevent XSS attacks. When your rich text content is processed bywordwrapAfter processing, if the template engine is not explicitly told that this content is safe HTML, it will escape the contents in it<p>/<strong>and tags like that&lt;p&gt;/&lt;strong&gt;, causing it to be displayed directly. The solution is towordwrap

Related articles

How to concatenate array elements into a string with a specified separator?

When operating a website, we often encounter the need to display a set of related data in the form of a list, such as multiple tags for articles, multiple keywords for product features, or multiple image URLs in an image library.At this time, if these scattered data elements can be integrated into a concise string and separated by specific symbols, it will greatly enhance the display effect and readability of the content.The Anqi CMS template engine provides a very practical `join` filter, which can easily meet this requirement.Understanding the `join` filter `join`

2025-11-09

How to split a string into an array with a specified separator?

In the daily operation of AnQi CMS, we often encounter the need to process some data stored as strings but actually containing multiple values.For example, an article may store multiple keywords in a comma-separated manner, or a custom content field may need to support multiple options, and these options are ultimately connected into a string with a specific symbol.In this case, we often need to split these strings using the preset delimiter into independent segments so that they can be displayed flexibly on the page or further processed.AnQi CMS based on the efficient architecture of Go language

2025-11-09

How to remove specific characters or HTML tags from a string?

In the daily content operation of AnQiCMS, we sometimes encounter situations where we need to finely process the content, such as removing specific characters, extra spaces, or stripping unnecessary HTML tags from the content.These operations are very critical for ensuring the neatness of content display, adapting to different front-end styles, and even for data cleaning.The AnQi CMS provides powerful template filter functions to help us efficiently complete these tasks.###

2025-11-09

How to calculate the number of times a specific keyword appears in a string or array?

In AnQiCMS content management practice, we often need to carry out refined analysis and optimization of website content.In which, calculating the number of times a specific keyword appears in an article, title, or dataset is a basic and important requirement.In order to evaluate SEO keyword density, analyze content quality, or conduct data statistics, AnQiCMS provides convenient and efficient solutions.This article will deeply explore how to utilize the built-in features of AnQiCMS to easily achieve this goal.### Core Tool: `count`

2025-11-09

How to define and use custom variables in a template?

In website operation, we often need to display diverse content, which may include system preset data, as well as customized personalized information based on business needs.AnQiCMS (AnQiCMS) fully understands this need, providing flexible and diverse mechanisms, allowing you to easily define and use custom variables in templates, thus achieving precise control and personalized display of content. This article will introduce you to the various methods of defining and using custom variables in AnQiCMS templates, helping you to fully utilize these features to create websites with more expressiveness and practicality.###

2025-11-09

How to include a common header, footer, or sidebar template file?

When building a website on Anqi CMS, we often encounter the need: the header (Header), footer (Footer), or sidebar (Sidebar) appear repeatedly on multiple pages.If you copy code every time, not only is it inefficient, but maintenance and updates will also become extremely complex. 幸运的是,AnQi CMS is developed based on Go language, its template engine supports syntax similar to Django, providing a very flexible and powerful way to introduce these public template files, helping us to achieve efficient content management and maintenance.

2025-11-09

How to create reusable template code snippets (macros)?

In the daily content operation of Anqi CMS, we often encounter some interface elements or code structures that need to be used repeatedly.For example, a standardized article list item, a product display card with a unified style, or a footer contact information with specific layout information.If writing this code manually every time, it is not only inefficient but also prone to inconsistent formatting issues.This is where the "Macro" feature provided by Anqi CMS becomes particularly important, as it helps us easily create reusable template code snippets, greatly enhancing the efficiency and quality of template development.###

2025-11-09

How to design a basic template and allow other pages to inherit it?

Building websites in AnQi CMS, efficient and flexible template design is the key to improving development efficiency and maintaining website consistency.Among them, designing a basic template and allowing other pages to inherit it is the core strategy to achieve this goal.AnQi CMS adopts a syntax similar to the Django template engine, making template inheritance intuitive and powerful. ### Lay the Foundation: Create Your Basic Template First, let's create the basic template skeleton of a website. In Anqi CMS, all template files are stored in the `/template` directory

2025-11-09