How to create and reference reusable code snippets (such as sidebars) in AnQiCMS templates?

Calendar 👁️ 62

As a senior security CMS website operator, I am well aware that efficiency and maintainability are the key to website content management in daily work.AnQiCMS provides a powerful and flexible template system, among which creating and referencing reusable code snippets is an important means to improve these aspects of efficiency.This not only reduces redundant labor, but also ensures the consistency of the overall style and function of the website, and also lays a solid foundation for future content updates and website redesigns.

A reusable code snippet in AnQiCMS template: core concept

AnQiCMS's template system is based on the Django template engine syntax in the Go language, which is similar to the Blade syntax we are familiar with, making it very friendly for content creators and developers.Under this template syntax, we can define variables, perform conditional judgments, execute loop controls, and more importantly, create and refer to reusable code snippets.

A reusable code snippet, as the name implies, refers to a code block that can be called multiple times on different pages of a website.For example, the sidebar, header, footer, copyright information, and even the display style of specific list items on a website can all be abstracted into reusable fragments.Using these snippets, we can avoid repeating the same HTML structure, CSS references, or JavaScript logic on each page, thus improving development efficiency and the convenience of later maintenance.

Organize your template files

To better organize reusable code snippets, AnQiCMS has agreed on a clear template directory structure. The root directory of the template is located/templateFolder, each set of templates should have an independent directory under it and contain aconfig.jsonfile definition template information.

Under this structure, the following are recommended practices for organizing reusable code snippets:

  • Public code (such asbash.html): Like the header (of a<head>) part, footer (of)<footer>The part, as well as almost all page structures that are inherited, are usually concentrated in a common file, such asbash.html. This file can be used as a "skeleton" or "master" for other page templates to inherit.
  • Code snippet directory (partial/): For those independent modules that appear repeatedly on multiple pages but are not the basic structure of the entire page, such as sidebars (sidebar.html), breadcrumb navigation (breadcrumb.html)、comment section or a specific content list display format,AnQiCMS recommends placing them in a folder namedpartial/In the subdirectory. This classification method makes the template structure clearer, easier to search and manage.

UtilizeincludeCode snippet embedded in tag

In the AnQiCMS template,includeTags are the most direct way to refer to independent code snippets. It allows us to insert the contents of an external template file into the specified position in the current template.

Suppose we have already beenpartial/A directory created a file namedsidebar.htmlwhich contains all the HTML structure and AnQiCMS tags of the sidebar, such as those used to display the latest article list, includingarchiveListLabel. Then, in the main template file (such asindex.htmlordetail.html), we can refer to it like this:

{% include "partial/sidebar.html" %}

If we need to pass specific variables toincludea specific code snippet, we can usewithKeyword. For example, if the sidebar needs atitlevariable to display its title:

{% include "partial/sidebar.html" with title="最新文章" %}

Insidebar.htmlin, you can use it directly.{{ title }}Get this value. If you want to pass only specific variables without inheriting all variables from the current template, you can addonlyKeyword:

{% include "partial/sidebar.html" with title="热门推荐" only %}

Moreover, if you are concerned that the template file referenced may not exist, which may cause the page to fail, you can useif_existsto make a judgment:

{% include "partial/sidebar.html" if_exists %}

so ifsidebar.htmlif it does not exist, it will not cause an error but will be ignored.

UsemacroCreate reusable components

macroTags provide a way to define reusable code blocks that are more similar to functions.It allows us to define a code snippet with parameters and then call it multiple times in the template, passing different parameters.This is very useful for those repeated components that have similar structures but different data.

For example, we can define a macro to display article list items instead of writing a long string of HTML:

{% macro article_item(article) %}
<li class="article-card">
    <a href="{{ article.Link }}">
        <img src="{{ article.Thumb }}" alt="{{ article.Title }}" />
        <h4>{{ article.Title }}</h4>
        <p>{{ article.Description|truncatechars:80 }}</p>
    </a>
</li>
{% endmacro %}

Then, use it in the templatearchiveListTagging the article list, you can call this macro to render each article item:

{% archiveList archives with type="list" limit="5" %}
    <ul>
    {% for item in archives %}
        {{ article_item(item) }}
    {% endfor %}
    </ul>
{% endarchiveList %}

macroIt can also be saved to an independent file, for example:macros.htmlThen proceedimportIntroduce tags into other templates, even set aliases for macros to further improve organization.

ByextendsandblockImplement template inheritance

Template inheritance is the cornerstone of the AnQiCMS template system for building complex layouts, it allows us to define a basic layout file (usuallybase.htmlIt includes the common structure of the website (such as header, footer, navigation, and sidebar areas), and then other page templates inherit this basic layout to overwrite or fill in the content of specific areas.

Inbase.htmlIn Chinese, we useblocktags to define areas that can be overridden by sub-templates:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}{% tdk with name="Title" siteName=true %}{% endblock %}</title>
    <!-- 其他头部资源引用 -->
</head>
<body>
    <header>{% include "partial/header.html" %}</header>

    <div class="main-content">
        <div class="container">
            <div class="row">
                <div class="col-md-9">
                    {% block content %}<!-- 页面主要内容区域 -->{% endblock %}
                </div>
                <div class="col-md-3">
                    {% block sidebar %}{% include "partial/sidebar.html" %}{% endblock %}
                </div>
            </div>
        </div>
    </div>

    <footer>{% include "partial/footer.html" %}</footer>
</body>
</html>

Note that here we willsidebaralso define as ablock, and default toincludeendedpartial/sidebar.htmlThis means that unless the sub-template explicitly overrides thissidebarblock, all inheritedbase.htmlpages will automatically display the default sidebar.

sub-template (for examplearticle_detail.htmlPassedextendsInherits tagsbase.htmlThen rewriteblockTo fill in their own content:

{% extends 'base.html' %}

{% block title %}{% archiveDetail with name="Title" %} - {% tdk with name="Title" siteName=false %}{% endblock %}

{% block content %}
    <article>
        <h1>{% archiveDetail with name="Title" %}</h1>
        <div>{% archiveDetail with name="Content"|safe %}</div>
    </article>
{% endblock %}

{% block sidebar %}
    {# 这个页面不需要侧边栏,或者需要一个不同的侧边栏 #}
    {% include "partial/another_sidebar.html" %}
{% endblock %}

It should be noted that,{% extends %}The label must be the first label in the template, otherwise the template inheritance will not work properly.

Reusable code snippets in practice

In actual operation, a common scenario is that we have a universal sidebar that is displayed on most pages, but on some specific pages (such as the home page, contact us page), it may need to hide or display different content.By means of the above mechanism, we can elegantly handle this situation.

  1. Create a universal sidebar snippetInpartial/Create in the directorydefault_sidebar.htmlIncluding the latest articles, popular tags and other general content.

    `twig<div class="

Related articles

How does the AnQiCMS template organize common code (such as header and footer)?

As an experienced CMS website operation personnel of an enterprise, I know that efficient content management cannot do without a well-organized and easy-to-maintain template system.In AnQi CMS, to better manage the public code of the website, such as the header (Header) and footer (Footer), the system provides a clear template organization structure and powerful template engine features.This not only improves the development efficiency, but also ensures the consistency and maintainability of website content.

2025-11-06

What do the two states represent for the `status` field in `config.`?

In AnQiCMS (AnQiCMS) template management system, the `config.` file plays a crucial role, acting like an ID card for the template, recording all basic information and current status of the template.The `status` field is the key indicator used by the system to identify whether a template is activated and in use.This field has only two possible values, each representing different meanings and uses, which are crucial for the normal operation of the website and the flexible management of templates.### Status 1: `status: 0`

2025-11-06

How to configure the display mode of the `template_type` field in `config.`?

As an experienced CMS website operation personnel, I am well aware of the importance of template configuration for website presentation and user experience.Today, let's delve into the `template_type` field in the `config.` file, which finely controls the display mode of your website template.In AnQi CMS, each template package core includes a configuration file named `config.`.This file is the 'identity certificate' of the template, which defines the name, version, author, and other basic information of the template. Among them

2025-11-06

When creating a new template, what are the required and optional fields in the `config.` file?

In Anqi CMS, creating a new website template is a key step to achieving personalized content display.The core of each template includes a `config.` configuration file, which is like the template's 'ID card', declaring the basic information, functional characteristics, and management status to the system.Familiarize yourself with the structure and field functions of the `config.` file, which is crucial for website operators and template developers, as it ensures that the template is correctly identified, managed, and applied by the system.

2025-11-06

What is the naming convention for the default homepage template file in AnQiCMS?

As an experienced CMS website operation personnel of an enterprise, I know that the naming specification of template files is crucial for the smooth operation and efficient management of the website.A clear naming convention not only ensures that the system renders the page correctly, but also greatly improves team collaboration and post-maintenance efficiency.Below, I will elaborate on the naming rules of the default home page template files in Anqi CMS.In AnQi CMS, all template files are stored in the `/template` folder under the system root directory.Each independent website template will be in `/template`

2025-11-06

How to create default templates for the model home page, document detail page, and list page of AnQiCMS?

As an experienced security CMS website operator, I am well aware of the importance of a clear and efficient template system for website content management.AnQiCMS provides a highly flexible and customizable template system that allows us to easily create personalized page layouts based on different business needs.Mastering the creation method of its default template is the foundation for efficient operation and content optimization.This article will detail how to create default templates for the model homepage, document detail page, and list page of AnQiCMS, with instructions on the use of key tags

2025-11-06

What is the default naming rule for single page detail page templates in AnQiCMS?

As an experienced CMS website operator for an enterprise, I am well aware that the exquisite presentation of content lies in the flexible application of templates.AnQiCMS as an efficient and customizable content management system provides us with powerful tools to shape every detail of the website, including the layout and style of single-page detail pages.Understanding the template naming rules is the foundation for efficiently managing and optimizing website content.

2025-11-06

How to use a custom template for specific documents, categories, or single pages in AnQiCMS?

As an experienced AnQiCMS (AnQiCMS) website operations personnel, I am well aware of the importance of content in attracting and retaining users, and the flexible template system is the key to achieving personalized content display.AnQiCMS provides powerful custom template features, allowing operation personnel to create unique page layouts and styles according to different content needs.### AnQiCMS Template Working Principle Overview AnQiCMS template system is based on Go language and adopts syntax similar to Django template engine, files are in the form of `

2025-11-06