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

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

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

    `twig