How to include other template files in AnQiCMS templates (such as public header/footer)?

In the daily operation of AnQiCMS, efficient content management is not only reflected in the background data processing, but also cannot do without flexible front-end template design.For website operators, isolating common components (such as navigation bars, footers, sidebars, etc.) and managing them independently, and introducing them to each page in a unified manner, is the key to improving work efficiency, maintaining website consistency, and simplifying maintenance.AnQiCMS provides a powerful and intuitive template introduction mechanism, making this process easy.

The AnQiCMS template system is based on Go language and draws on the syntax of the Django template engine, which is very friendly to template developers and operators. All template files use.htmlas the suffix, and store them uniformly in/templateUnder the directory. The static resources required by the template, such as styles, JavaScript scripts, and images, are collected independently./public/static/In the directory, clear separation helps organize and manage the content.

Template structure and public parts agreement

AnQiCMS encourages modular design of templates. Each template needs its own independent folder under the root directory of the template.Inside these folders, in order to facilitate management and reuse, there are some basic conventions:

  • Public code file (bash.html): The header (header), footer (footer) and other common parts that almost every page needs to inherit or reference are usually placed in a file namedbash.htmlThe file. This file can be used as the basic skeleton of the website, and other pages can be expanded on this basis.
  • Code snippet directory (partial/)Some smaller, reusable code snippets, such as sidebar content, breadcrumb navigation, ad slots, etc., can be stored centrally.partial/Under the directory. Simply introduce it when you need these fragments.

This structure ensures the clarity and maintainability of the template, making it simple and efficient to adjust common elements in large websites or multi-site management.

Core mechanism: the introduction and reuse of templates.

AnQiCMS provides various tags to implement the inclusion, inheritance, and code reuse of template files, including the most commonly used ones.include/extendsandmacro.

UseincludeTags to include common code snippets

includeThe tag is the most direct way to reuse code snippets. It allows you to insert the content of one HTML file into a specified position in another HTML file.This is very effective for introducing the common parts of the page, such as header navigation, footer copyright information, etc.

The basic usage is to put the path to the target template file in double quotes:

{% include "partial/header.html" %}
{% include "partial/footer.html" %}

Assuming yourpartialThere is one in the directoryheader.htmlA file that contains the website's top navigation and Logo elements, you can use the above method to include it in any page template.

To enhance the robustness of the template, you can useif_existsparameters. When the template file being imported may not exist, useif_existsit can prevent the page from throwing an error, and the system will directly ignore the import:

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

includeThe tag also supports passing throughwithParameters are passed to the template being introduced. This allows the imported fragment to display different content based on the page context it is called in:

{% include "partial/header.html" with title="这是声明给header使用的title" keywords="这是声明给header使用的keywords" %}

Inheader.htmlIn the template, you can use{{title}}and{{keywords}}to retrieve these values.

If you want the template to only access throughwithYou can use the variables passed explicitly, without inheriting all the variables of the current template, toonlyparameters:

{% include "partial/header.html" with title="这是声明给header使用的title" keywords="这是声明给header使用的keywords" only %}

UtilizeextendsTag-based template inheritance

extendsThe tag is used to build a parent-child template structure, which is more suitable for defining the overall layout or 'skeleton' of a page. It is through a basic layout template (usually referred to asbase.html),You can define the common structure of the page and useblocktags to mark the areas that can change. The child template inherits this basic template and optionally overrides theseblockarea.

A typicalbase.htmlIt may include the following structure:

<!DOCTYPE html>
<html lang="{% system with name='Language' %}">
<head>
    <meta charset="UTF-8">
    {% block title %}<title>{% tdk with name='Title' %}</title>{% endblock %}
    <link rel="stylesheet" href="{% system with name='TemplateUrl' %}/css/style.css">
    {# 可以在这里引入公共的header片段 #}
    {% include "partial/top_header.html" %}
</head>
<body>
    <div id="wrapper">
        <header>
            {% block header_content %}
                {# 默认的头部内容,子模板可以覆盖 #}
            {% endblock %}
        </header>

        <nav>
            {% block nav_content %}
                {# 导航条内容 #}
            {% endblock %}
        </nav>

        <main id="main-content">
            {% block main_body_content %}
                {# 页面主体内容 #}
                <p>这里是默认的主体内容。</p>
            {% endblock %}
        </main>

        <footer>
            {% block footer_content %}
                {# 可以在这里引入公共的footer片段 #}
                {% include "partial/bottom_footer.html" %}
            {% endblock %}
        </footer>
    </div>
</body>
</html>

On any page that needs to use this layout (such asindex.htmlorarchive/detail.html), you just need to{% extends 'base.html' %}declare inheritance and then rewrite the correspondingblockand it is done:

{% extends 'base.html' %}

{% block title %}
    <title>我的首页 - AnQiCMS</title>
{% endblock %}

{% block main_body_content %}
    <h2>欢迎来到我的网站!</h2>
    <p>这是首页的独有内容。</p>
    {# 可以在这里引入其他片段 #}
    {% include "partial/latest_articles.html" %}
{% endblock %}

It is worth noting that,extendsThe tag must be the first tag in the template file, otherwise, template inheritance will not work properly.

macrotag to define reusable code blocks

macroTags are used to define a reusable code block, similar to functions in programming languages.It accepts parameters and can only access these passed parameters, making it very suitable for creating independent UI components or complex HTML structures that appear repeatedly.

For example, you can define one to display list items in articlesmacro:

{% macro archive_item(archive) %}
<li class="article-list-item">
    <a href="{{ archive.Link }}" class="item-link">
        <img src="{{ archive.Thumb }}" alt="{{ archive.Title }}" class="item-thumbnail">
        <h3 class="item-title">{{ archive.Title }}</h3>
        <p class="item-description">{{ archive.Description }}</p>
    </a>
</li>
{% endmacro %}

Then, you can use this in your page templatemacro:

{% import "macros/archive.macro" archive_item %} {# 假设宏定义在 macros/archive.macro 文件中 #}

<ul>
{% for item in archives %}
    {{ archive_item(item) }}
{% endfor %}
</ul>

Byimportstatement, you can include one or more from external filesmacro. Multiple macros can be separated by commas or also usedasKeywords are used to set aliases for macros.

Template organization and **practice

AnQiCMS provides two ways to organize template files, namely 'folder organization mode' and 'flattened file organization mode'. Regardless of which mode is chosen, public elements such as headers, footers, sidebars, and so on are extracted and stored separately.partial/Under the directory, they are all good practices.

  • Page header (partial/header.htmlorbash.html): Includes<head>Public area<meta>tags,<link>Style references,<script>Script references, as well as the navigation bar, Logo at the top of the page.
  • Footer (partial/footer.htmlorbash.html): Includes copyright information, filing number, friend links, statistics code, etc.
  • Sidebar (partial/sidebar.html): Includes popular articles, latest comments, advertisements, and other dynamic content.

Through these mechanisms, website operators can easily maintain the public parts of the website, ensuring consistency of brand image and user experience, while also greatly reducing the workload of template modification and updates.

Summary

In AnQiCMS, the modular design and reuse mechanism of templates is a powerful tool to improve website operation efficiency. By using flexiblyincludeintroducing code snippets,extendsBuild the page layout and as wellmacroCreate reusable components, you can build a website with clear structure, easy maintenance and rich features.This not only simplifies content publishing and page optimization work, but also provides a solid foundation for quickly responding to reader needs and website iteration.

Frequently Asked Questions (FAQ)

Q1: I have modifiedheader.htmlThe file, but the website page did not update, what is the matter? A1:AnQiCMS To enhance performance, it will cache template files.If you do not see the changes taking effect immediately after modifying the template file, it is usually necessary to clear the system cache.You can manually clear the cache in the "Update Cache" feature of the AnQiCMS backend.In addition, browser cache may also cause this problem, try to force refresh the page (Ctrl+F5 or Cmd+Shift+R) or clear the browser cache.

Q2: I want to introduce the same one on different pagespartialHow do I make a file display different content? A2:You can useincludelabel'swithPass parameters to the includedpartialPass different variables to the file. For example, if you have apartial/ads.htmlUsed to display ads, you can pass it when introducingad_typeVariable:{% include "partial/ads.html" with ad_type="homepage_banner" %}Inpartial/ads.htmlIn, you can use{% if ad_type == "homepage_banner" %}And other logic to display the corresponding content.

Q3:extendsandincludeWhat is the difference, when should I use them? A3: extendsUsed to establish the inheritance relationship of templates, defining the overall "skeleton" or "master template" of a page. A page can onlyextendsa parent template, and the definition ofblockFill in your own content within the area. It is suitable for defining the overall layout, navigation, footer, and other common structures of the page.includeIt focuses more on inserting small, independent, reusable code snippets into any position of any template. A template canincludeMultiple files, and without inheritance. It is suitable for introducing sidebars, comment sections, advertising spaces, copyright information, and other local modules. In short,extendsDefine the page structure,includeFill the page content blocks.