In daily website operations, especially when publishing long-form content, adding a clear table of contents (or content navigation) is crucial for improving user experience.It can not only help visitors quickly understand the structure of the article, conveniently jump to the chapters of interest, but also optimize the page SEO performance to a certain extent.AnQiCMS provides a very practical feature that allows us to easily implement the directory display of article content in the front-end template.

Understand how AnQiCMS generates the article directory

When AnQiCMS processes article content, it will intelligently parse the title tags in the content (such as<h1>/<h2>/<h3>These title information is extracted and provided to the front-end template in a structured data form, which is what we callContentTitles. This feature is particularly suitable for article detail pages, allowing visitors to understand the structure of the article at a glance.

Steps to display the article catalog in the front-end template.

Display the article catalog in the AnQiCMS front-end template, mainly involving locating template files, obtaining catalog data, and iterating over and rendering these data.

First step: Locate the article detail page template

First, we need to find the template file corresponding to the article detail page. According to the template production conventions of AnQiCMS, the template for the article detail page is usually located in the template directory under{模型table}/detail.htmlOr you can set a custom template file for a specific article or category in the background.

Second step: usearchiveDetailtag to obtainContentTitlesdata

In the article detail page template, AnQiCMS providesarchiveDetailTags to get the detailed information of the current article, which includesContentTitles.ContentTitlesReturns an array (a slice in Go language), where each element represents a title within the article content and includes the following key information:

  • Title: The text content of the title.
  • Tag: The HTML tag type of the title, for example, "H2", "H3", etc.
  • Level: The level of the title, usually H1 is level 1, H2 is level 2, and so on.
  • Prefix: The prefix may exist in the title, such as automatically generated serial numbers '1.' or '1.1.' and so on.

You can obtain this data in the following ways:

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

Here, we will assign the directory data obtained tocontentTitlesThis variable for future use.

Third step: Render the directory by looping through

obtaining tocontentTitlesAfter the variable, because it is an array, we need to use the AnQiCMS template engine'sforLoop the tag to iterate over it and render each title information to the page. When rendering, we can combine each title'sTagandLevelproperties to control the hierarchical display and style of the catalog.

For example, you can build your article table of contents like this:

{# 假设您在文章详情页的侧边栏或内容顶部显示目录 #}

{%- archiveDetail contentTitles with name="ContentTitles" %} {# 获取当前文章的目录数据,并赋值给 contentTitles 变量 #}
{%- if contentTitles %} {# 只有当存在目录数据时才显示目录框 #}
<div class="article-toc"> {# 这是目录的容器,您可以根据需要添加CSS类进行样式控制 #}
    <h3>文章目录</h3>
    <nav>
        <ul>
        {% for item in contentTitles %}
            {#
                item.Tag: 标题的HTML标签,如"H2", "H3"
                item.Level: 标题的层级,如2, 3
                item.Prefix: 标题前缀,如"1.", "1.1."
                item.Title: 标题的纯文本内容
                `slugify` 过滤器是假设存在的一个用于生成URL友好ID的过滤器。
                如果AnQiCMS模板中没有内置类似功能,您可能需要手动确保HTML内容中的标题有对应的ID,或者使用JavaScript在前端动态生成锚点。
            #}
            <li class="toc-item toc-{{ item.Tag | lower }}" style="margin-left: {{ (item.Level - 1) * 15 }}px;">
                <a href="#{{ item.Tag | lower }}-{{ item.Title | slugify }}">{{ item.Prefix }} {{ item.Title }}</a>
            </li>
        {% endfor %}
        </ul>
    </nav>
</div>
{%- endif %}

In the above code, we:

  • Use{%- ... %}Syntax to remove the blank lines generated by tags, keeping the HTML output neat.
  • By{% if contentTitles %}Determine, ensure that the table of contents is displayed only when the article indeed has a title.
  • Added for each catalog item.toc-itemandtoc-h2CSS class for (or any other tag name), as well as based onitem.Levelinline.margin-leftStyle, so that the directory hierarchy can be easily implemented through CSS.
  • With<a>label'shrefThe attribute generated an anchor link.It should be noted that in order for this anchor link to be valid, the actual title (such as<h2>文章标题</h2>) in your article content must also have a correspondingidproperties, such as<h2 id="h2-文章标题">文章标题</h2>. AnQiCMS usually automatically adds an ID to the title during content rendering, but you may need to confirm or consult the detailed development documentation in actual tests.In order to generate a URL-friendly ID, we assume that the example usesslugifyFilter, if AnQiCMS does not provide it, you may need to handle it yourself.

Further optimization and beautification

  • CSS style customization:You can modify it according to your website design,.article-toc/.toc-item/.toc-h2Adjust the font, color, background, indentation, and other appearances of the directory with CSS classes.
  • JavaScript interaction:To provide a better user experience, you can also introduce JavaScript code to implement:
    • Smooth scrolling:When you click on the catalog item, the page will smoothly scroll to the corresponding section.
    • Highlight the current chapter:Automatically highlight the directory items within the visible area of the current screen as the user scrolls the page.
    • Fold/expand the catalog:For articles with many title levels, provide the function of collapsing and expanding the directory.

By following these steps and optimization suggestions, you can easily implement a functional and aesthetically pleasing article catalog in the AnQiCMS frontend template, thereby significantly enhancing the reading experience of the website's content.


Frequently Asked Questions (FAQ)

  1. Why did the directory not display on the front-end page even though I followed the steps to add the code?Firstly, please confirm whether your article content actually uses H1, H2, H3, and other title tags. AnQiCMS'sContentTitlesThe function is to extract catalog information based on these title tags.Next, check if you have added code in the template file of the article detail page, and ensure that the file path and code itself do not have any syntax errors.Finally, if your article content is entered through a Markdown editor, please make sure that the Markdown editor support is enabled in the global settings of the backend.

  2. Why does the page fail to jump to the corresponding title location after clicking on the directory item?This is usually because of the directory link'shrefattribute (anchor) not matching the actual title in the article content.idThe attribute does not match. In order for the anchor jump to take effect, the value of each directory item must match the<a>label'shreffor example#h2-文章标题) must match the attribute value of the correspondingidfor example<h2 id="h2-文章标题">文章标题</h2>) Consistent. AnQiCMS usually intelligently generates IDs for titles in content, but in some custom cases, you may need to check and ensure they match.If AnQiCMS does not automatically add an ID to the title, you may need to modify the article content or use JavaScript dynamically to add an ID to the title on the front end.

  3. How to implement smooth scrolling to a page section when clicking on a catalog item instead of a jarring jump?To achieve smooth scrolling, you need to use front-end JavaScript. You can take advantage of the methods provided by modern browsers.scrollIntoView()of the method.behavior: 'smooth'Option, or introduce a lightweight JavaScript library (such as jQuery'sanimate()Implement this by method. You need to write JavaScript code to listen for the directory item click event, then get the target anchor, and call the corresponding scrolling method.At the same time, it can also be combined with listening to the page scroll event to highlight the currently visible directory item