As an experienced CMS website operation personnel of an enterprise, I fully understand the importance of efficient content management and flexible template customization for website operation.In daily work, we often need to deal with various page elements, such as sidebars, breadcrumb navigation, headers and footers, etc., which appear repeatedly on multiple pages.It is crucial to modularize and reuse these commonly used code snippets to improve development efficiency, ensure code consistency, and simplify maintenance work.AnQi CMS provides a powerful and easy-to-use template engine, allowing us to easily achieve this goal.

In Anqi CMS, the reuse of templates is mainly centered around the syntax similar to the Django template engine, and combined with a specific directory structure to organize reusable code snippets. All template files use.htmlas the suffix, and store them uniformly in/templateUnder the directory. To better manage code snippets, we usually create a named directory under each template theme.partial/The subdirectory, specifically used to store these reusable code snippets, such as the sidebar (sidebar.html) bread crumb navigation (breadcrumb.html) comment form (comment.html) and so on.

Create and reference reusable code snippets

AnQi CMS template engine providesincludeLabel, this is the core mechanism for realizing code fragment reuse.includeLabels allow us to embed the content of a template file into another template file, thus avoiding code redundancy.

1. Create reusable sidebar code snippets

The sidebar is a common element on a website, usually containing categories, navigation, latest articles, popular tags, links, or contact information.We can encapsulate this content in a separate template file and then reference it on pages where a sidebar needs to be displayed.

First, in your template theme directory (for example/template/您的主题名称/), create a subdirectory namedpartial/folder, and create a new file, for examplesidebar.html.

Insidebar.htmlIn the file, we can use various tags provided by Anqi CMS to dynamically fill in content. For example, we can display a list of article categories, the latest articles, and the contact information of the website:

{# partial/sidebar.html 内容示例 #}
<aside class="sidebar">
    <div class="widget">
        <h3>文章分类</h3>
        <ul>
            {% categoryList categories with moduleId="1" parentId="0" %}
                {% for category in categories %}
                    <li><a href="{{ category.Link }}">{{ category.Title }}</a></li>
                {% endfor %}
            {% endcategoryList %}
        </ul>
    </div>

    <div class="widget">
        <h3>最新文章</h3>
        <ul>
            {% archiveList latestArchives with moduleId="1" order="id desc" limit="5" %}
                {% for archive in latestArchives %}
                    <li><a href="{{ archive.Link }}">{{ archive.Title }}</a></li>
                {% endfor %}
            {% endarchiveList %}
        </ul>
    </div>

    <div class="widget">
        <h3>联系我们</h3>
        <p>电话:{% contact with name="Cellphone" %}</p>
        <p>邮箱:{% contact with name="Email" %}</p>
        <p>地址:{% contact with name="Address" %}</p>
    </div>
</aside>

Create itsidebar.htmlAfter that, you can reference it in any page template that needs to display a sidebar. For example, in the article detail pagearticle/detail.htmlor list pagearticle/list.htmlyou can use it like thisincludeTags:

{# article/detail.html 或 article/list.html 内容示例 #}
{% extends 'bash.html' %} {# 假设您有一个基础布局模板 #}

{% block content %}
    <div class="main-content">
        {# 页面主要内容区域 #}
        <article>
            <!-- 文章内容 -->
        </article>
    </div>
    
    {# 引用侧边栏 #}
    {% include "partial/sidebar.html" %}
{% endblock %}

Thus,sidebar.htmlAll the content will be embedded into{% include "partial/sidebar.html" %}the position.

2. Create reusable breadcrumb navigation code snippets

Breadcrumbs navigation is very important for improving user experience and website SEO, as it can clearly show the user's position on the website.In AnQi CMS, breadcrumb navigation is usually dynamically generated, and we can encapsulate it in a reusable fragment.

Similarly, inpartial/Create a file namedbreadcrumb.html.

Inbreadcrumb.htmlthe file, we will use Anqie CMS'sbreadcrumbLabel to get breadcrumb data and throughforLoop through and display:

{# partial/breadcrumb.html 内容示例 #}
<nav class="breadcrumb">
    {% breadcrumb crumbs with index="首页" title=true %}
        <ul>
            {% for item in crumbs %}
                <li>
                    {% if not forloop.Last %} {# 判断是否是最后一个链接,最后一个通常不需要链接 #}
                        <a href="{{ item.Link }}">{{ item.Name }}</a>
                        <span>&gt;</span>
                    {% else %}
                        <span>{{ item.Name }}</span>
                    {% endif %}
                </li>
            {% endfor %}
        </ul>
    {% endbreadcrumb %}
</nav>

Then, reference it in the page template where breadcrumb navigation is required. For example, at the top of an article detail page or a category list page:

{# article/detail.html 或 category/list.html 内容示例 #}
{% extends 'bash.html' %}

{% block content %}
    {# 引用面包屑导航 #}
    {% include "partial/breadcrumb.html" %}

    <div class="main-content">
        {# 页面主要内容区域 #}
        <!-- ... -->
    </div>
{% endblock %}

In this way, no matter whether it is an article page, a product page, or other category page, as long as it is referencedbreadcrumb.htmlit can automatically display the correct navigation path.

3. A more advanced reuse mechanism: template inheritance and macros

exceptincludeTags, Anqi CMS also supportsextendsandmacroAnd more advanced reuse mechanisms can further improve the flexibility and maintainability of templates.

  • Template inheritance (extends): For the overall layout of the website (such as the header, footer, main content area framework), we usually create onebase.htmlas the 'skeleton' template. All other page templates go through{% extends 'base.html' %}Inherit this skeleton and proceed through{% block content %}Using these tags to rewrite the content of specific areas. In this way, the common parts such as headers and footers can be placedbase.htmlUnified management, all inherited pages will automatically have these elements.

  • Macro function (macro): When you need to reuse a small piece of HTML structure in a template, and this structure will differ according to the data passed in,macroIt is very useful. It is similar to functions in programming languages, where parameters can be defined and different HTML can be generated based on the input parameters.For example, you can define a macro to render a list item with a title and link, and in differentarchiveListorcategoryListcall it in the loop.

Summary

Creating and referencing reusable code snippets such as sidebars, breadcrumbs, and others in AnQi CMS is crucial for improving website operation efficiency and template management level. By reasonably planning the template structure, public elements can be extracted topartial/directory, and make use ofinclude/extendsandmacroThe template tags can not only greatly reduce redundant code but also ensure the consistency of the website style. When adjustments are needed, only one modification is required to affect the entire site, greatly simplifying the maintenance and iteration of the website.High-quality code reuse allows content operation personnel to focus more on content creation and optimization, rather than繁琐 (tedious) template code.


Frequently Asked Questions (FAQ)

1. Which code snippets should I abstract into reusable components?Any HTML structure that appears repeatedly on multiple pages should be considered for abstraction into reusable components.This includes but is not limited to: the website header navigation, footer information, sidebar content (such as the latest articles, popular categories), breadcrumb navigation, copyright statement, ad code, social media share buttons, and any widgets with fixed styles and dynamic content.The principle is that if a code block appears on at least two pages and its structure is relatively stable, then it is worth being reused.

2. Why did I passincludeThe referenced template file content is not displayed correctly, or the variables have not been passed?First, please checkincludeIs the file path referenced in the tag correct, make sure it matches/templateThe actual path under the directory. Secondly,includeThe tag defaults to inheriting all variables from the current template. If you want to pass only specific variables, or to avoid variable conflicts, you can usewithandonlykeywords. For example,{% include "partial/header.html" with title="我的标题" only %}Only willtitlepass the variable toheader.htmlIf the content is an HTML structure, make sure to use the output variable when using it to prevent the content from being escaped and not displayed correctly in HTML.|safeFilter, for example{{ archiveContent|safe }}To prevent the content from being escaped and not displayed correctly in HTML, make sure to use the output variable when using it.

3.includeandextendsWhat are the differences between tags, and how should I choose to use them? extendsTags are used to implement template inheritance, defining a basic page layout (such asbase.html),including all shared page structures (header, footer, CSS/JS references, etc.), and usesblocktag defines the content area that can be overwritten by sub-templates. Sub-templates passextendsInherit the basic layout, then use the same namedblocktags to fill or modify these areas.includeTags are used to embed an independent, smaller code snippet (such as a sidebar, breadcrumb) into a specific location in any template. In simple terms,extendsUsed to construct the "skeleton" of the page, andincludeUsed to fill a specific "muscle" or "organ" in the "skeleton". If your code snippet is part of the overall page layout and shared across pages, considerextendsConsider if it is an independent functional module within the page;include.