When operating a website, we sometimes encounter such a requirement: when pure text content is inputted in the background, we hope it can be displayed with line numbers in the front-end. This is very helpful for displaying code, poetry, configuration scripts, or any text content that needs to be read line by line.Although AnQiCMS backend content entry is very convenient, how can we automatically add beautiful line numbers to this plain text content when it is displayed on the front end?The flexible template engine of Anqi CMS can help us easily achieve this.

Understanding the source of content and basic processing

Firstly, 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'.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 }}

Here are thearticleContentthe variable contains the text you enter 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 content, we will mainly use a filter namedlinenumbersThe filter. This filter will process the text content line by line, and automatically add line number prefixes such as '1. ', '2. ' before each line.

Process content that may contain HTML tags

很多时候,我们从AnQiCMS后台输入的内容并非纯粹的文本,即使看起来是纯文本,后台的富文本编辑器或Markdown编辑器也可能会在其中添加一些HTML标签,例如<div>/<p>/<span>English. If you directly apply the content containing these HTML tagslinenumbersFilter that also numbers HTML tags as a line, which is usually not what we want, making line numbering confusing.

To solve this problem, we need to apply in the applicationlinenumbersBefore the filter, strip all HTML tags from the content to make it truly plain text. Anqi CMS provides a very practicalstriptagsFilter, it 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 a chained use of filters:

{{ articleContent | striptags | linenumbers }}

Ensure correct rendering:safeFilter

When you have appliedlinenumbersAfter the filter, the output content will be like1. 这是第一行This format. AnQiCMS template engine, for security reasons, defaults to escaping special characters in output content (such as</>)Escape to prevent cross-site scripting attacks (XSS).This means, if you do not handle it, the browser may interpret '1.' asThese content are displayed as normal strings, rather than being rendered as HTML.

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

Therefore, the complete processing process is:内容 -> Remove HTML tags -> Add line numbers -> Mark as safe HTML.

The final filter chain looks like this:

{{ articleContent | striptags | linenumbers | safe }}

Example of integration solution

Let's look at a complete example, suppose you have published an article in the background, the content is multi-line plain text or text containing simple HTML, and you want to display it on the article detail page (archive/detail.htmlor custom article template) shows content with line numbers.

In your template file (for example)template/default/archive/detail.html), find the part that displays the article content and make changes:

<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 obtain{%- archiveDetail articleContent with name="Content" %}Get the article content into a variable namedarticleContent.{%-is used to avoid unnecessary whitespace in this line.

Then, in<pre><code>...</code></pre>Inside the tag, we usearticleContentvariables in sequence.striptags/linenumbersandsafethree filters.

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

Use<pre>Labels are used to preserve the original format of the content, especially spaces and newline characters,<code>labels indicate that this is code content, which helps with semanticization.

some style beautification suggestions

linenumbersThe default line number style generated by the filter may be quite simple, for example1.If you want the line numbers to be displayed more beautifully, you can customize them 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 itself does not directly wrap the line numbers<span>The tag, it only adds at the beginning of each line of text1.Such a prefix. Therefore, if you need to have more refined CSS control over line numbers, you may consider using JavaScript to dynamically handle it on the front end, or accept the default output format andpreandcodeThe style of the label indirectly affects the overall presentation.

Through these steps, you can automatically present the plain text content input in the AnQiCMS backend in a clear format with line numbers in the front-end template.


Common Questions and Answers (FAQ)

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

A1:In theory, if the content is definitely completely free of HTML tags and plain text,striptagsThe filter is not necessary. But to ensure compatibility, especially when you are unsure whether the background content will be "polluted" by the rich text editor, it is added.striptagsis a safer choice, it will not have any negative impact on plain text, it will only strip away any existing HTML tags, ensuringlinenumbersthe filter only processes plain text content.

Q2:linenumbersFilter output line number style can be customized, can it? For example, I want to[1]Instead1..

A2:linenumbersFilter currently defaults to using “1.2.auto auto auto auto auto[1]),may need to combine custom JavaScript or more complex template logic to achieve this. At the CSS level, you can adjustpreandcodeThe style of the label, for example, setting text color, line height, padding, etc., to indirectly beautify the display effect of line numbers.

Q3:I only want to add line numbers to a specific paragraph in the article content, not the entire content, can it be done?

A3:Yes.linenumbersThe filter acts on the entire string.