In AnQiCMS front-end template, dynamically display the document content title: Loop and Application of ContentTitles

When using AnQiCMS for website content operation, we often need to provide users with a better reading experience and navigation convenience. One very practical feature is the automatic generation of an article table of contents (Table of Contents). AnQiCMS has given this aspect a lot of thought, as it can automatically extract titles from the document content and present them asContentTitlesThe form is provided for use in the front-end template. Today, let's delve deeper into how to loop and display these in your AnQiCMS front-end template.ContentTitles.

Understand deeply ContentTitles: The magic of document content titles

First, let us make it clearContentTitlesWhat is it. When you edit document content in the AnQiCMS backend, you will usually use H1, H2, H3 and other title tags to organize the article structure.AnQiCMS is very smart in automatically parsing and collecting the titles in these contents, generating a list that includes all hierarchical titles, which isContentTitlesIt is not a fixed field of the article, but is dynamically generated according to the content of the article.

This feature significantly helps improve user experience and SEO:

  • Enhancing user experienceReaders can clearly see the overall structure of the article and quickly locate the chapters of interest.
  • Optimize SEOA well-structured article with a table of contents is easier for search engines to understand and helps improve the ranking of the article.

ContentTitlesReturns an array (or more precisely, a list), where each element is an object containing title information. Each object typically includes the following key attributes:

  • Title: The actual text content of the title.
  • Tag: The HTML tag used for the title, for example.h2/h3.
  • Level: The level of the title, the smaller the number, the higher the level (for example,)h1is Level 1,h2The Level is 2).
  • PrefixIf the title has a serial number prefix (e.g., “1.1 AnQiCMS Introduction”), it will include “1.1”.

How to obtain the ContentTitles data source

In the AnQiCMS front-end template, you need to obtainContentTitlesdata, we need to usearchiveDetailThe tag is used to obtain detailed information about the current document.

If you are on a document detail page, for exampledetail.htmlthenarchiveDetailThe tag automatically retrieves the document data of the current page. We just need to passname="ContentTitles"the parameter, and we can specify that we want to retrieve the list of document titles.

For example, you can define a variable in this waycontentTitlesto carry all the titles extracted from the current document:

{% archiveDetail contentTitles with name="ContentTitles" %}
    {# 在这里,contentTitles 变量就已经包含了文档的标题列表 #}
    {% comment %} 后续我们将在这个标签内部,或者在其作用域内使用 contentTitles {% endcomment %}
{% endarchiveDetail %}

If you want to get a document with a specific ID:ContentTitlesyou can also do so byidto specify the parameters:

{% archiveDetail otherContentTitles with name="ContentTitles" id="10" %}
    {# otherContentTitles 变量将包含ID为10的文档的标题列表 #}
{% endarchiveDetail %}

Loop and display: Display the title on the page

Once we pass througharchiveDetailTags obtainedContentTitlesList, next is how to loop through the list in the template and display it beautifully. AnQiCMS template engine supports syntax similar to Django templates, so we can useforLoop tags to process.

Generally, we would organize these titles into an article outline. Here is a basic code example showing how to loopcontentTitlesand display each title:

{% archiveDetail contentTitles with name="ContentTitles" %}
    {% if contentTitles %} {# 确保有标题才显示目录 #}
        <div class="article-toc">
            <h3>文章目录</h3>
            <ul>
                {% for item in contentTitles %}
                    {# 利用item.Level来控制缩进,这里简单地乘以一个像素值 #}
                    <li class="{{item.Tag}}" style="margin-left: {{ item.Level|add:-1|mul:20 }}px;">
                        {# 通常会为每个标题生成一个可点击的链接,并指向文章正文对应的锚点 #}
                        {# 注意:这里的锚点(#heading-{{ loop.index }})需要在文章正文中手动添加对应ID,或通过JavaScript动态生成 #}
                        <a href="#heading-{{ loop.index }}">
                            {% if item.Prefix %}{{item.Prefix}} {% endif %}{{item.Title}}
                        </a>
                    </li>
                {% endfor %}
            </ul>
        </div>
    {% endif %}
{% endarchiveDetail %}

In this code, we:

  • Use{% if contentTitles %}To judgecontentTitlesIs empty, to avoid displaying an empty directory when there is no title.
  • Use{% for item in contentTitles %}Traverse each title object.
  • item.TagCan be used as a CSS class name, making it easy to target title tags such ash2/h3Perform different style designs.
  • item.LevelCan be used to control the indentation of the directory, simulating the level structure of the title.We utilize the built-in filter of AnQiCMS, reducing the level by 1 (since h1 usually does not need indentation), and then multiplying it by a pixel value to achieve a visual sense of hierarchy.
  • item.PrefixOptionally display the serial number before the title.
  • item.TitleThis is the actual text of the title.

Please note the example mentioned abovehref="#heading-{{ loop.index }}"This is a commonly used practice to create internal jump links in article contents. To make these links truly functional, you need to add the corresponding links to the actual title elements in the body of the article.idProperty. For example, ifloop.indexIs1, then the first title of the article body (such as a<h2>tag must beid="heading-1"This usually requires you to manually add it in the background, or through some frontend scripts or backend processing to dynamically implement it.

Combined with practical application: further thoughts

  1. Style and structure: You can addarticle-tocandliTo define rich CSS styles for elements, such as setting different font sizes, colors, or using borders, background colors to beautify the catalog.item.Taganditem.LevelProvided good granularity for controlling the display effect of different level titles.
  2. Interactive catalog: By combining a little JavaScript, you can make the article outline more interactive.For example, when the user scrolls the page, the title currently being read in the catalog will automatically highlight;Or click on the directory item to smoothly scroll to the corresponding position.
  3. Content editing specification: In order toContentTitlesThe function performs to its maximum effectiveness, when editing articles in the background, it is essential to develop good habits, use appropriate HTML title tags (H1/H2/H3Organize content structure with) instead of just through bold or changing font size. The standard HTML structure is correctly extracted by AnQiCMSContentTitlesThe foundation of it.

By using these flexible tags and simple loop logic, you can easily implement dynamic article catalogs in the AnQiCMS website's front-end template, greatly enhancing the professionalism and user-friendliness of the website content.


Frequently Asked Questions (FAQ)

  1. Ask: Why does my article content already use H tags, butContentTitlesDoes not display any content?

    • Answer: This may be because your article content does not use the standardH1toH6Labels are used to define titles, or these title contents are very short. AnQiCMS will generate according to the HTML title tags identified in the background content editor.ContentTitlesPlease check the content of your article to ensure that the title is as HTML<h2>>/<h3>>Structure rather than just through style is presented. At the same time, if the article title is very short or only one, the system may also consider it unnecessary to generate a table of contents.
  2. Question: Can I control?ContentTitlesDo you want to display titles of specific levels, such as only displaying H2 and H3?

    • Yes, of course. In template loopcontentTitlesYou can use the AnQiCMS template engine when listing.ifLogic judgment label, according toitem.Leveloritem.TagFilter properties. For example, to display only H2 and H3 headings, you can modify the code inside the loop like this:
      
      {% for item in contentTitles %}
          {% if item.Level == 2 or item.Level == 3 %}
              <li class="{{item.Tag}}" style="margin-left: {{ item.Level|add:-1|mul:20 }}px;">
                  <a href="#heading-{{ loop.index }}">
                      {% if item.Prefix %}{{item.Prefix}} {% endif %}{{item.Title}}
                  </a>
              </li>
          {% endif %}
      {% endfor %}
      
  3. Question:ContentTitlesHow can I jump to the corresponding position of the article text after clicking on the generated catalog item?

    • Answer: To implement the jump to the catalog item click, you need to make sure that each actual title element in the article body has a uniqueidProperty, and thisidof the catalog item'shrefThe property values match. A common practice is to, in yourarchiveDetailtag outputContentWhen content is processed through some backend or JavaScript dynamically adds an ID to the H tags in the text. For example, if your catalog item link ishref="#heading-1"Then the first title of the article needs to haveid="heading-1". You can use JavaScript to traverse the H in the text.