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

Calendar 👁️ 109

How to effectively organize the structure of long articles when using Anqi CMS to manage website content, and improve the reading experience of readers, is a question worth paying attention to.Automatically generate the 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 they are interested in, and also helps search engines better understand the structure of the article.

AnQi CMS provides support for Markdown syntax in content management and cleverly utilizes this feature to extract title hierarchy information from Markdown content, thereby generating a navigable article directory. This means that as long as you use Markdown headings reasonably while editing the article, ...#/##/###etc.), the system can help us build this directory.

Open the Markdown editor: preperation

Before starting to generate the table of contents, we need to make sure that the Markdown editor function has been enabled in the AnQi CMS backend.This setting is usually found in "Background->Global Settings->Content Settings".After enabling, the content of the article you edit will be recognized by the system as Markdown format, and subsequent parsing will be performed.

Core Mechanism: How does AnQiCMS parse Markdown content

The strength of AnQi CMS lies in its template engine's deep parsing capability for Markdown content. When you write articles using Markdown syntax, for example:

# 这是一个一级标题
## 这是二级标题
### 这是三级标题

The system not only converts these Markdown headings to corresponding HTML tags when rendering articles,<h1>/<h2>/<h3>It will also extract the metadata of these titles. This metadata is througharchiveDetailin the labelContentTitlesThe field is exposed to the template, it is an array object that contains the text of each title, the HTML tag type (such as h1, h2), level, and possibly a custom prefix. It is thisContentTitlesArray, it provides the basic data for automatically generating the catalog.

Build the article catalog (TOC) in the template.

We need to display these extracted title information as clickable article contents in the corresponding template file, usually in the article detail page template (such as{模型table}/detail.htmlbeing performed.

First, througharchiveDetailTags to retrieve articles.ContentTitlesData:

{% archiveDetail contentTitles with name="ContentTitles" %}

IfcontentTitlesThe array is not empty, indicating that the article contains a title. At this point, we can start building the table of contents. Below is a simple code example showing how to traverseContentTitlesGenerate a basic directory:

{% archiveDetail contentTitles with name="ContentTitles" %}
{% if contentTitles %}
<nav class="article-toc">
    <h3>文章目录</h3>
    <ul>
        {% for item in contentTitles %}
        <li class="toc-level-{{ item.Level }}">
            <a href="#{{ item.Title|urlencode|lower|replace:" ","-" }}" title="{{ item.Title }}">
                {% if item.Prefix %}{{ item.Prefix }} {% endif %}{{ item.Title }}
            </a>
        </li>
        {% endfor %}
    </ul>
</nav>
{% endif %}

Let's explain this piece of code:

  1. {% archiveDetail contentTitles with name="ContentTitles" %}: This line of code retrieves the list of all titles from the details of the current article and assigns it tocontentTitlesVariable.
  2. {% if contentTitles %}: Determine if the article has a title, and render the table of contents only if it exists to avoid empty tables of contents.
  3. <nav class="article-toc">...</nav>: This is a semantic HTML tag used to wrap the article catalog for easy styling control with CSS.
  4. {% for item in contentTitles %}: TraversecontentTitlesEach item in the array.
  5. <li class="toc-level-{{ item.Level }}">: Generate a list item for each directory item and according toitem.Level(Header levels, such as 1 representing h1, 2 representing h2) Add different CSS classes, which helps us control the indentation and appearance of the catalog through style sheets, making it more hierarchical.
  6. <a href="#{{ item.Title|urlencode|lower|replace:" ","-" }}" title="{{ item.Title }}">: This is the core part of the directory item, create a hyperlink.
    • href="#...": The target of the link is an in-page anchor. We assume that the Anqi CMS Markdown parser will automatically convert the Markdown headings to HTML whenhAdd a tag with an ID based on the title text (such as## My HeadingIt will be rendered as:<h2 id="my-heading">My Heading</h2>)
    • item.Title|urlencode|lower|replace:" ","-": To ensure that the generated anchor ID is valid, weitem.Titlehave performed several processes:
      • urlencode: Encode special characters in the title to avoid link errors.
      • lower: Convert the title to lowercase.
      • replace:" ","-": Replace spaces in the title with hyphens.-This is a common way to generate URL slugs and anchor IDs.
    • title="{{ item.Title }}"AddtitleAttribute, providing hover tips.
  7. {% if item.Prefix %}{{ item.Prefix }} {% endif %}{{ item.Title }}: Display the text content of the title.item.PrefixOptional, if present, it will be displayed.

Suggestion for style adjustment:

To make the article directory beautiful and easy to use on the page, you can adjust it through CSS..article-tocand.toc-level-XDefine styles for classes, for example, set borders, background colors, font sizes, indents, etc., to maintain consistency with the overall design style of the website.

/* 示例 CSS 样式 */
.article-toc {
    border: 1px solid #eee;
    padding: 15px;
    margin-bottom: 20px;
    background-color: #f9f9f9;
}
.article-toc h3 {
    font-size: 18px;
    margin-top: 0;
    margin-bottom: 10px;
    color: #333;
}
.article-toc ul {
    list-style: none;
    padding-left: 0;
}
.article-toc ul li {
    line-height: 1.8;
}
/* 不同层级标题的缩进 */
.toc-level-1 { padding-left: 0; font-weight: bold; }
.toc-level-2 { padding-left: 15px; }
.toc-level-3 { padding-left: 30px; }
.toc-level-4 { padding-left: 45px; }
/* ...更多层级 */

Practical skills and precautions

  • Standard use of Markdown titlesEnsure that the author of the article always follows the semantic use of Markdown headings when writing content, that is, the first-level heading is used for the main theme of the article, and the second and third-level headings are used for chapter division, with clear levels.
  • The choice of catalog location: The article catalog is usually placed at the beginning of the article content or in the sidebar, so that readers can see it at a glance. You can throughincludeLabel this directory code in the appropriate position in the article detail template.
  • CompatibilityThe above method relies on the built-in Markdown parser of Anqi CMS to automatically add predictable ID attributes to the generated HTML titles. If you encounter a problem where the directory links cannot be clicked to jump, you may need to check whether the Markdown renderer provides

Related articles

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 to introduce the necessary JavaScript library for Markdown rendering in the `base.html` file?

AnQiCMS provides a convenient and efficient Markdown editor for content creators, allowing us to easily organize article structure, insert code blocks, and images.However, when our content needs to display complex mathematical formulas or clear flowcharts, relying solely on the Markdown syntax itself is not enough to present them beautifully on the web.These advanced features require the introduction of specific JavaScript libraries on the browser side to be correctly parsed and rendered.

2025-11-08

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

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 summary 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 often breaks the original tag structure, causing the page layout to become chaotic, even resulting in unclosed tags, which seriously affects the user experience.AnQi CMS as an efficient

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