How to automatically add line numbers to plain text content entered in the background of AnQiCMS template?

Calendar 👁️ 64

When operating a website, we sometimes encounter the need: to display line numbers automatically for plain text content entered in the backend, which is very helpful for displaying code, poetry, configuration scripts, or any text content that needs to be read line by line.Although the AnQiCMS backend content entry is very convenient, how can these plain text contents be automatically numbered with beautiful line numbers when displayed on the front end?The flexible template engine of AnQi CMS can help us easily achieve this.

Understanding the source and processing of content

First, we need to clarify the source of these plain text content.In AnQiCMS, you usually enter these texts through the 'Content' field of documents or single pages in 'Document Management' or 'Page Management'.This content is usually passed through the front-end template,archiveDetailorpageDetailsuch tags to get. For example, if you want to get the detailed content of the article, it might be written like this:

{% archiveDetail articleContent with name="Content" %}
{{ articleContent }}

HerearticleContentThe variable contains the text you entered from the background.

AnQiCMS's template engine supports syntax similar to Django templates and Blade templates, which includes a rich set of filters (filters) that can be used to process variables. To add line numbers to the content, we mainly use a named filter calledlinenumbersThis filter processes the text content line by line and automatically adds a prefix of "1. " or "2. " before each line.

Process content that may contain HTML tags

At times, we input content from the AnQiCMS backend that is not pure text, even if it appears to be plain text, the rich text editor or Markdown editor in the backend may also add some HTML tags, such as<div>/<p>/<span>If you apply the content containing these HTML tags directlylinenumbersA filter that also numbers HTML tags on a line, which is usually not what we want, as it can make line numbering confusing.

In order to solve this problem, we need to apply in the applicationlinenumbersBefore the filter, all HTML tags in the content should be stripped off to make it truly plain text. Anqi CMS provides a very practicalstriptagsA filter that can effectively strip all HTML tags from a string.

So, the processing flow becomes:Content -> Strip HTML tags -> Add line numbers.

In the template, this will be reflected as the chained use of filters:

{{ articleContent | striptags | linenumbers }}

Ensure correct rendering:safeFilter

When you applylinenumbersAfter the filter, the output content will be like1. 这是第一行This format. The AnQiCMS template engine, for security reasons, defaults to escaping special characters (such as</>Escape characters to prevent cross-site scripting (XSS).This means that if you do not process it, the browser may display the content such as '1. ' as plain text, rather than rendering it as HTML.

At this time, we need to usesafeThe filter tells the template engine that this content is safe, it can be output directly as HTML, and the browser can parse and display it according to the HTML specification.safeFilters are usually placed at the end of all other filters to ensure that the final output content is processed correctly.

So, the complete processing procedure is:Content -> Remove HTML tags -> Add line numbers -> Mark as safe HTML.

The final filter chain looks like this:

{{ articleContent | striptags | linenumbers | safe }}

Integration solution example

Let's look at a complete example, assuming you have published an article in the background, the content is multiline plain text or text containing simple HTML, you want to show on the article details page (archive/detail.htmlOr customize the article template) to display content with line numbers.

In your template file (for exampletemplate/default/archive/detail.html), find the section that displays the article content and make the modification:

<article class="article-detail">
    <h1>{% archiveDetail with name="Title" %}</h1>
    <div class="article-meta">
        <span>发布日期:{% archiveDetail with name="CreatedTime" format="2006-01-02" %}</span>
        <span>浏览量:{% archiveDetail with name="Views" %}</span>
        <!-- 其他文章元信息 -->
    </div>

    <div class="article-content-with-line-numbers">
        {%- archiveDetail articleContent with name="Content" %}
        <pre class="line-numbers-pre"><code>{{ articleContent | striptags | linenumbers | safe }}</code></pre>
    </div>

    <!-- 上一篇/下一篇、相关文章等其他内容 -->
</article>

In the above code, we first obtained the article list through{%- archiveDetail articleContent with name="Content" %}Get the article content into a variable namedarticleContent.{%-The use is to avoid unnecessary whitespace in this line.

Next, in<pre><code>...</code></pre>the tag, we appliedarticleContentThe variables are used in order.striptags/linenumbersandsafeThree filters.

  • striptagsEnsure the content is plain text.
  • linenumbersAdd numbering to each line.
  • safeLet the browser render the text with line numbers as HTML correctly.

Use<pre>Tags are used to preserve the original format of the content, especially spaces and line breaks,<code>Tags indicate that this is code content, which helps with semanticization.

Some suggestions for style beautification

linenumbersThe line number style generated by the filter by default may be quite simple, for example1.. If you want the line numbers to look more beautiful, you can customize it with CSS. For example, you can set different colors, fonts, or alignment for the line numbers and content.

/* 在您的 style.css 文件中添加 */
.line-numbers-pre {
    background-color: #f8f8f8;
    border: 1px solid #ddd;
    padding: 15px;
    margin-bottom: 20px;
    overflow-x: auto; /* 确保长行可以滚动 */
    white-space: pre-wrap; /* 保留空白符和换行符 */
}

.line-numbers-pre code {
    display: block; /* 确保每行独立显示 */
    font-family: monospace;
    line-height: 1.6;
    color: #333;
}

.line-numbers-pre code span.line-number { /* 假设linenumbers会给行号一个span */
    color: #999;
    margin-right: 10px;
    text-align: right;
    display: inline-block; /* 让行号保持独立 */
    min-width: 30px; /* 确保行号有足够的宽度 */
}

Please note,linenumbersThe filter does not wrap the line numbers directly<span>The tag, it only adds before each line of text1.such a prefix. Therefore, if you need to perform more precise CSS control over line numbers, you may consider using JavaScript to dynamically process it on the frontend, or accept its default output format and process it throughpreandcodeThe style of the label indirectly affects the overall presentation.

By following these steps, you can make the plain text content entered in the AnQiCMS backend automatically displayed in a clear numbered format on the front-end template.


Frequently Asked Questions (FAQ)

Q1: If my content is already plain text, do I need to usestriptagsfilter?

A1: In theory, if the content is determined to be completely without any HTML tags, striptagsThe filter is not necessary. But to ensure compatibility, especially when you are not sure whether the background content will be 'polluted' by the rich text editor, add it.striptagsIt is a safer choice, it will not have any negative impact on plain text, it will only strip any existing HTML tags, ensuringlinenumbersThe filter only processes plain text content.

Q2:linenumbersCan the line number style of the filter output be customized? For example, I want[1]instead of1..

A2: linenumbersThe filter currently defaults to using “1.Hello World2.such a format add line numbers and do not provide parameters to directly modify the line number format. If you need a more advanced line number format (such as[1]),May require combining with custom JavaScript or more complex template logic. On the CSS level, you can adjustpreandcodeThe style of the label, such as setting text color, line height, padding, etc., to indirectly beautify the display effect of line numbers.

Q3: Can I add line numbers only to a specific paragraph in the article content, not the entire content, is it possible?

A3: Yes, it can.linenumbersThe filter acts on the entire string.

Related articles

How to automatically render the multi-line text (including newline characters) of AnQiCMS custom fields into HTML tags `<p>` and `<br/>`?

When using AnQiCMS to manage website content, we often take advantage of its powerful custom field features to enrich page information.Especially for text that needs to include multiline descriptions, notes, or detailed explanations, the 'Multiline Text' type in custom fields is undoubtedly the ideal choice.However, when we eagerly display these text contents with line breaks on the front-end page, we may find that the original line breaks are not automatically recognized by the browser, resulting in all the text being cramped together, greatly reducing the reading experience.This is actually a feature of HTML rendering mechanism

2025-11-07

How to implement the `replace` filter of AnQiCMS for batch replacement of sensitive words in article content?

In the field of content management, the flexibility and maintainability of website content are crucial.Batch replacement of article content is an efficient and practical operation, whether it is for brand unification, information update, or sensitive word filtering.AnQiCMS as a rich-featured enterprise-level content management system, provides a variety of content processing mechanisms, among which the `replace` filter and the background content batch replacement feature play a key role in different scenarios.

2025-11-07

How to concatenate or add two strings or numbers in AnQiCMS template?

In AnQi CMS template design, dynamically combining text information or performing calculations on numerical values is a common requirement.It is crucial to be able to handle string concatenation and numeric addition operations flexibly, whether it is to build personalized product descriptions or to display dynamic data on the page.The Anqi CMS template system, drawing on the syntax of the Django template engine, provides a variety of intuitive and powerful methods to complete these tasks.

2025-11-07

How to determine if a number (such as article ID) can be evenly divided by a specific number in the AnQiCMS template?

In website content display, we often encounter some special requirements, such as wanting to apply different styles to specific elements in the list, or to make some distinctions based on the parity of the article ID.AnQiCMS is a powerful template engine, drawing inspiration from the excellent design of Django templates, and provides a simple and efficient way to handle these logic.Today, let's discuss a very practical feature in the template: how to determine if a certain number (such as the article ID) can be evenly divided by a specific number.

2025-11-07

How to print the complete type and value of a variable during the development and debugging of AnQiCMS templates for problem troubleshooting?

During the development and debugging of AnQiCMS templates, we often encounter such situations: the page displays incorrectly, or some data is not displayed as expected.At this time, we hope to 'penetrate' the variables in the template and understand what types they are and what specific values they contain.In fact, only by mastering the true state of variables can one accurately locate the problem.AnQiCMS's template system adopts syntax similar to Django template engine, which makes variable output and logical control intuitive.In templates, we usually use double curly braces `{{ variable name

2025-11-07

What are the practical scenarios for the AnQiCMS `phone2numeric` filter? How to convert letters on a phone keyboard to numbers?

In the operation of daily websites, we often encounter situations where we need to process various types of data and display them in a user-friendly manner.A phone number is a typical example. Sometimes, for marketing or brand promotion, we may see some "vanity numbers" composed of letters and numbers, such as "1-800-FLOWERS".These numbers are easy to remember, but users still need to manually convert them to pure digits when dialing.AnQi CMS as a powerful enterprise-level content management system

2025-11-07

How to generate a specified number of random text placeholders when there is no actual content in the AnQiCMS template?

During the development of website templates, we often encounter such situations: the interface layout has been completed, but the actual content data is not ready.At this time, in order to ensure that the layout and visual effects of the front-end page can be accurately presented, we need some placeholder text to fill the page, simulating the existence of real content.AnQi CMS fully considers this requirement and provides a very practical template tag - `lorem`, which can help us easily generate a specified number of random texts.

2025-11-07

How to repeat a specific string (such as a separator) multiple times in the AnQiCMS template?

In web template design, we often encounter the need to repeatedly output a specific string or character pattern to achieve visual separation, emphasis, or layout effects.For example, you may want to display a line composed of multiple dashes between content blocks, or repeat asterisks to decorate an area.In the AnQiCMS template system, thanks to its syntax similar to the Django template engine, achieving such repeated output is very flexible and efficient.

2025-11-07