How to extract the HTML content rendered from Markdown without destroying the tag structure?

Calendar 👁️ 93

In content operation, we often encounter such needs: on a list page of articles or a special topic page, it is necessary to display the abstract content of the articles.These articles are usually written using a Markdown editor, which may contain images, links, bold text, and other rich HTML structures.If simply truncating the HTML string rendered by Markdown, it will often destroy the original tag structure, causing the page layout to become chaotic, even appearing unclosed tags, which seriously affects the user experience.

AnQi CMS is an efficient and flexible content management system that fully considers the challenges of this type of content display.It provides an elegant solution through its powerful template engine and built-in filter functions, ensuring that the tag structure remains intact and damage-free when extracting the HTML content rendered from Markdown.

Understand the Markdown content rendering in AnQi CMS

Firstly, we need to understand how Anqi CMS handles Markdown content.When we use the Markdown editor in the background to write articles, the system will store the Markdown text.When displaying this content on the front-end page, especially on complete content pages like document detail pages, Markdown text is usually rendered into HTML.

In the AnQi CMS template, we can usearchiveDetailTag to get various fields of the article, including the content field of the Markdown editorContent. ThisContentThe field has a very practicalrenderparameter. When we setrender=trueWhen, the system will automatically convert and render the stored Markdown text into standard HTML content. If rendering is not required, it can be set torender=falseThis parameter can be omitted when the editor is closed, at this timeContentThe field will output the original Markdown text.

For example, we can use it like this to get the rendered article content:{% archiveDetail articleContent with name="Content" render=true %}

It should be noted that the rendered HTML content, when output in the template to avoid being escaped again by the browser and displayed as plain text, needs to be accompanied by|safeThe filter is used. This is a common security practice in web development.|safeTell the template engine that this content is safe HTML and can be output directly.

Core Strategy: Smart Extraction of HTML Content

Now, we have obtained the rendered HTML content, but problems arise if we directly truncate the HTML string in characters or words. For example, a segment of HTML<p>这是一段<b>重要的</b>文字。</p>If we interrupt the characters 'Zhuanyao' in the middle<b>The tags cannot be closed, and the browser will try to fix it, but the result is often unpredictable, causing the layout to be chaotic.

To solve this problem, AnQi CMS has built-in truncation filters specifically designed to handle HTML content:truncatechars_htmlandtruncatewords_html.

  • truncatechars_html:numberThis filter will truncate HTML content based on the specified character count, while also intelligently checking and closing all unclosed HTML tags.It ensures that the truncated HTML is still a valid, structurally complete fragment, and adds an ellipsis “…” at the truncation position.
  • truncatewords_html:number: withtruncatechars_htmlSimilar, but it truncates HTML content based on the specified word count. It also handles the closing of HTML tags and adds an ellipsis.

These filters are the key to extracting HTML content without damaging the tag structure.

Practice exercise: Extract the HTML content rendered by Markdown.

Assuming we are building a list page of articles, each article needs to display a summary of about 150 characters, and we hope to retain the original HTML styles such as bold and italic in the Markdown summary.

In our template file, you can write it like this:

{# 假设我们正在遍历一个文章列表,item是当前文章对象 #}
{% for item in archives %}
    <div class="article-summary">
        <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
        <div class="summary-content">
            {# 先获取并渲染Markdown内容为HTML #}
            {%- archiveDetail fullContent with name="Content" id=item.Id render=true %}
            {# 对渲染后的HTML内容进行字符截断,并确保安全输出 #}
            {{ fullContent|truncatechars_html:150|safe }}
        </div>
        <a href="{{ item.Link }}" class="read-more">阅读更多 &gt;</a>
    </div>
{% endfor %}

In the code above:

  1. We first pass through{% archiveDetail fullContent with name="Content" id=item.Id render=true %}Got the specified article'sContentfield content and force it to be rendered as HTML. The rendered HTML content is assigned tofullContentVariable.
  2. Then, we handlefullContentthe variable was used|truncatechars_html:150Filter. This filter intelligently truncates the first 150 characters of HTML content (including the characters occupied by HTML tags themselves), and most importantly, it automatically handles the potential unclosed tags caused by truncation positions and closes them correctly.
  3. Finally, we used it again|safeA filter to ensure that the extracted and processed HTML summary can be normally parsed and displayed by the browser, rather than being output as plain text.

In this way, we can see the brief abstracts of each article on the article list page, which not only retains the original HTML format but also avoids the problem of tag structure damage caused by truncation, keeping the page layout neat.

Further considerations: When to choose which cutting method

  • Character-based cutting (truncatechars_html)When you have a strict character limit on the length of summaries, such as requiring that all summaries be kept within 100 characters, regardless of whether the content is Chinese, English, or HTML tags, truncatechars_htmlIt would be a more precise choice.
  • Cut by word (truncatewords_html): If your website content is mainly in English and you want the summary to be semantically complete, avoid cutting words in the middle, thentruncatewords_htmlIt will be more suitable. It will try to truncate at word boundaries to make the summary more readable.
  • Get plain text summary (striptags): Sometimes, we may not need to retain any HTML styles and just want a plain text summary. In this case, we can use|striptagsA filter that removes all HTML tags, then you can truncate the plain text you get|truncatecharsor|truncatewordsFor example:{{ fullContent|striptags|truncatechars:150 }}.

These built-in features of AnQi CMS provide great convenience for content operators.No need to manually clean HTML, nor worry about complex regular expressions, just call the corresponding tags and filters in the template, and you can easily achieve a high-quality content summary display.

Frequently Asked Questions (FAQ)

How to get the original Markdown content instead of the rendered HTML?If you want to get the original text of Markdown content on the front-end page, rather than the rendered HTML, you canarchiveDetailput in the tag.renderthe parameter tofalse. For example:{% archiveDetail rawMarkdown with name="Content" render=false %}At thisrawMarkdownThe variable stores the original Markdown text without conversion.

2. How can I get a plain text summary without retaining any HTML tags?If you want the summary to be plain text without any HTML tags, you can first use|striptagsThe filter removes all HTML tags and then truncates characters or words. For example, extract a plain text summary of 150 characters:{% archiveDetail fullContent with name="Content" render=true %} {{ fullContent|striptags|truncatechars:150 }}Here, Markdown is rendered into HTML first, then the HTML tags are stripped, and finally the plain text is truncated.

3. Why while usingtruncatechars_htmlortruncatewords_htmlAfter that, it still needs to be added|safeFilter?The template engine of AnQiCMS (similar to Django) defaults to escaping all output content to prevent cross-site scripting attacks (XSS) and other security issues. This means that eventruncatechars_htmlortruncatewords_htmlThe filter has intelligently handled the closing of HTML tags, generating a valid HTML fragment, if missing|safeFilter, these HTML tags (such as<p>/<b>The closing parenthesis will be escaped as entity encoding (for example&lt;p&gt;/&lt;b&gt;), resulting in the browser being unable to correctly parse and render. Add a|safeThis is to explicitly inform the template engine that this content has been verified and can be directly output as HTML.

Related articles

How to automatically generate an article table of contents (TOC) based on Markdown content?

How to effectively organize the structure of long articles while managing website content with Anqi CMS, which is a worthy issue to pay attention to.Automatically generate an article table of contents (Table of Contents, abbreviated as TOC) is a very practical solution.It not only allows readers to quickly understand the outline of the article, but also makes it convenient for them to jump to the parts of interest, while also helping search engines better understand the structure of the article.

2025-11-08

How to implement syntax highlighting for code blocks in Markdown content rendered to HTML?

In Anqi CMS, managing content, especially documents containing code, you may want to display code blocks in a beautiful and easy-to-read manner, which usually requires syntax highlighting.Markdown is a lightweight markup language that makes content creation simple and efficient, and the built-in Markdown editor of Anqí CMS is even more powerful.How can code blocks in Markdown content be syntax highlighted when rendered into HTML?

2025-11-08

Does AnQiCMS support the configuration of a custom Markdown renderer?

In the daily operation of AnQiCMS, we often encounter refined needs for content presentation, especially for those who are accustomed to writing content in Markdown, it is natural to be concerned about whether the system supports the configuration of custom Markdown renderers.In fact, Markdown, with its concise and efficient features, has become the preferred choice for many content creators.From the design philosophy of AnQi CMS, it is committed to providing an efficient, customizable, and easy-to-expand content management solution.

2025-11-08

How to troubleshoot exceptions when displaying mathematical formulas or flowcharts in a Markdown editor on the front end?

In Anqi CMS, the Markdown editor brings us great convenience, especially when we need to insert mathematical formulas or draw flowcharts.By concise syntax, we can easily express complex concepts.However, sometimes after using these advanced features, they may not display as expected, but instead display exceptions, such as only displaying the original Markdown text, or some content cannot be parsed.Don't worry when encountering such problems. This is usually not a problem with the safety CMS itself, but rather a problem with some link in the configuration, content writing, or frontend loading process.

2025-11-08

How does the `truncatechars_html` filter precisely control the character truncation length of HTML content?

In website operation, how to effectively display content is an eternal topic.We hope users can quickly browse information and also be attracted by the精彩的 abstract, and then click to view the full text.However, when the original content is long and contains complex HTML structures, how to elegantly reduce it has become a challenge that template designers and content operators often encounter.Bluntly cutting a segment of text with HTML tags by character count may destroy the original HTML structure.

2025-11-08

How to safely truncate a Markdown-rendered HTML content by words?

In content operation, we often need to display a brief version of the content on list pages, aggregation pages, or article summary areas.This not only optimizes the page layout and improves user experience, but also helps search engines better understand the content theme to some extent.However, when content is written in Markdown format and finally rendered as HTML, if you need to truncate it, you may encounter some challenges.It is easy to truncate HTML content by characters or bytes, which can easily lead to incomplete tags, disordered page structure, and even display errors.

2025-11-08

How to remove all or specified HTML tags from the HTML content rendered from Markdown?

When managing content in Anqi CMS, we often use the Markdown editor to conveniently write articles.The power of Markdown lies in its ability to convert simple plain text format into rich HTML structure, which brings great convenience to the style and expressiveness of content.But sometimes, we do not need or do not want these HTML tags to be completely displayed on the final page.

2025-11-08

How to convert newline characters to `<br/>` in Markdown rendered plain text content?

In website content management, we often encounter such a situation: after hard work in the background editor, we press the enter key between each line of text, hoping that they will maintain the same line break effect on the front page.However, after the content was published, it was found that all the line breaks had disappeared and the text was squeezed into a ball.This is because web browsers default to treating consecutive newline characters as a single space and do not automatically convert them into visually apparent line breaks.For friends using AnQiCMS, solving this problem is actually very simple and elegant

2025-11-08