How to create and reference reusable code snippets like sidebars, breadcrumbs, etc. in templates?

Calendar 👁️ 67

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.

Related articles

How should common code snippets like headers, footers, etc. be organized and stored during template creation?

As a website operator familiar with Anqi CMS, I am well aware of the importance of a well-structured and easy-to-maintain template for the long-term healthy operation of the website.How to efficiently organize and store common page headers, footers, and other reusable code snippets during template creation is crucial for improving development efficiency and ensuring website consistency.In Anqi CMS, the template system uses a syntax similar to the Django template engine, which provides us with powerful tools to achieve code reuse and modular management.

2025-11-06

How to control the enable status of the template through the `status` field in `config.`?

In the daily operation of Anqi CMS, we often need to adjust the appearance and layout of the website, which usually involves switching or enabling different templates.AnQi CMS provides an intuitive and efficient way to manage the enabled status of templates, which is mainly achieved through the `status` field in the `config.` file under each template directory.

2025-11-06

What are the possible values and their meanings for the `template_type` field in `config.`?

As an experienced CMS website operation personnel, I fully understand the importance of template configuration for the front-end display and user experience of the website.The `config.` file is the core configuration file for each AnQiCMS template, defining its various basic properties and behaviors.Among them, the `template_type` field plays a crucial role, directly affecting the display of the website on different devices.

2025-11-06

How to define a new template, what is the role of the `config.` file?

As an experienced CMS website operation personnel, I am well aware that a flexible and efficient template system is crucial for the presentation of website content and user experience.The AnQi CMS was designed with full consideration of the customizability and ease of use of the templates, allowing both beginners and experienced developers to easily handle it.Next, I will elaborate on how to define a new template in Anqi CMS and deeply analyze the core role played by the `config.` file in this process.

2025-11-06

What should the default naming of the homepage template file be?

As an experienced CMS website operation personnel, I fully understand the importance of the homepage in attracting and retaining users. It is the first impression of users visiting the website and also the core hub of content layout and information communication.For Anqi CMS, understanding the naming conventions of its template files, especially the default naming of the homepage template file, is the foundation for ensuring the smooth operation and efficient management of the website.The Anqi CMS system defaults to identifying the homepage template file as `index.html`.This file is the entry point of your current theme template

2025-11-06

What is the default naming rule for the template files of the model home page, document detail page, and document list page?

As an experienced CMS website operation personnel of an enterprise security, I know that a clear and efficient template naming rule is crucial for the management of website content and user experience.AnQi CMS provides great flexibility in template design and also establishes a set of default naming conventions, which is very helpful for us to quickly build and iterate web pages.In AnQi CMS, all template files are named with a `.html` extension and are uniformly stored in the `/template` folder under the system root directory.

2025-11-06

How can I customize the templates for 404, 500 error pages, and site shutdown notification pages?

As a senior security CMS website operator, I fully understand the importance of every user touch point, including those unusual pages, in carrying the brand image and user experience.A meticulously customized 404, 500 error pages, and site shutdown notification pages, which not only enhance the professionalism of the website but also provide guidance to users when they encounter problems, effectively reduce the bounce rate, and maintain a good search engine impression. Next, we will discuss in detail how to customize these special pages in Anqi CMS.

2025-11-06

What are the differences between the 'Folder mode' and 'Flat mode' in the template file organization pattern?

As a senior security CMS website operations personnel, I am well aware of the importance of template file organization methods for website post-maintenance, content release efficiency, and team collaboration.In AnQi CMS, the organization mode of template files is mainly divided into two types: 'folder mode' and 'flattened mode', each with its own characteristics and suitable for different project needs and team habits.Understanding the differences between these two patterns can help us better choose and manage templates.First, let's delve deeper into the **folder organization pattern**.

2025-11-06