How to include a common header, footer, or sidebar template file?

Calendar 👁️ 87

When building a website on Anqi CMS, we often encounter the need: the header (Header), footer (Footer), or sidebar (Sidebar) appear repeatedly on multiple pages.If you copy code every time, it is not only inefficient, but the subsequent maintenance and updates will also become extremely complex.Fortunately, AnQi CMS is developed based on Go language, its template engine supports syntax similar to Django, providing a very flexible and powerful way to introduce these public template files, helping us to achieve efficient content management and maintenance.

The core concept lies in the reusability and structuring of code. By modularizing repetitive content, we can ensure consistency in website style, reduce redundant code, and greatly simplify future content update work.The AnQi CMS mainly achieves this goal through two mechanisms:includeTags andextends.

1. UseincludeTag inclusion code snippet

includeLabels are used to embed independent, smaller code snippets where needed.You can imagine it as 'paste' another piece of pre-written code at a certain location.This approach is very suitable for introducing components that are relatively independent in page structure and have clear functions, such as website sidebars, common ad slots, contact information modules, or simple headers and footers.

Usage scenario:

  • Sidebar (Sidebar):Most pages may share the same sidebar, which includes navigation, popular articles, advertisements, etc.
  • Part of the header/footer content:For example, the copyright information area, friend link list.
  • Independent functional module:For example, a page's comment form, share button group.

How to operate:

Firstly, save your public code snippet as an independent.htmlFile. Usually, to better organize template files, we will place these fragments in the directory of the current theme template.partial/folder. For example, you cantemplate/你的主题名/partial/Create in the directorysidebar.htmlorfooter_links.html.

Suppose we created apartial/sidebar.htmlfile, the content is as follows:

<aside class="sidebar">
    <h3>最新文章</h3>
    <ul>
        {% archiveList archives with type="list" limit="5" %}
            {% for item in archives %}
                <li><a href="{{item.Link}}">{{item.Title}}</a></li>
            {% endfor %}
        {% endarchiveList %}
    </ul>
    <h3>联系我们</h3>
    <p>电话:{% contact with name="Cellphone" %}</p>
    <p>邮箱:{% contact with name="Email" %}</p>
</aside>

Then use it in the page template where you need to display this sidebar{% include %}Label to introduce it:

<!-- index.html 或 detail.html 等页面中 -->
<div class="main-content">
    <!-- 页面主体内容 -->
</div>
<div class="right-sidebar">
    {% include "partial/sidebar.html" %}
</div>

For more flexible usage:

  • Optional introduction:If a segment may exist or may not exist, you can useif_existsTo avoid errors:
    
    {% include "partial/ad_banner.html" if_exists %}
    
  • Pass data:You can even giveincludePass specific variables to the template, so it can display different content:
    
    {% include "partial/hero_section.html" with title="欢迎访问安企CMS" subtitle="高效易用的内容管理系统" %}
    
    Inhero_section.htmlYou can use it in{{ title }}and{{ subtitle }}you can directly use

2. Useextendstags to build the page skeleton

extendsThe tag is used to define a generic page skeleton or layout, which the child pages can inherit and only modify specific content blocks.This is like an architectural blueprint, where you define the basic structure of the house (walls, roof), and then you can freely decorate (fill in the content) in each room (sub-page).This approach is very suitable for managing the overall layout of a website, including the global header, footer, and main area division.

Usage scenario:

  • The overall layout of the website:Define a containing<head>Area, main navigation, main content area, footer copyright information, and other inclusions:base.html.
  • Layouts of different page types:For example, the article detail page and product list page may share most of the layout, but the structure of the main content area will be different.

How to operate:

First, create a basic layout file, usually namedbase.htmlPlace it in the root directory of your theme template. In thisbase.htmlUse{% block 块名称 %}{% endblock %}to define the content areas that can be overridden by child templates.

Onebase.htmlAn example might look like this:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}{% tdk with name="Title" siteName=true %}{% endblock %}</title>
    <meta name="keywords" content="{% tdk with name="Keywords" %}">
    <meta name="description" content="{% tdk with name="Description" %}">
    <link rel="stylesheet" href="{% system with name="TemplateUrl" %}/css/main.css">
    {% block head_extra %}{% endblock %} {# 留给子模板添加额外CSS/JS #}
</head>
<body>
    <header class="header">
        <a href="{% system with name="BaseUrl" %}"><img src="{% system with name="SiteLogo" %}" alt="{% system with name="SiteName" %}"></a>
        <nav class="main-nav">
            {% navList navs %}
                <ul>
                    {% for item in navs %}
                        <li><a href="{{ item.Link }}">{{item.Title}}</a></li>
                    {% endfor %}
                </ul>
            {% endnavList %}
        </nav>
    </header>

    <main class="container">
        <div class="content-wrapper">
            {% block content %}{% endblock %} {# 这是主内容区域,子模板会在这里填充 #}
        </div>
        {% include "partial/sidebar.html" %} {# 这里可以再次使用include引入侧边栏 #}
    </main>

    <footer class="footer">
        <p>&copy; {% now "2006" %} {% system with name="SiteName" %}. All rights reserved.</p>
        <p>{% system with name="SiteCopyright" %}</p>
        {% block footer_extra %}{% endblock %} {# 留给子模板添加额外JS #}
    </footer>
</body>
</html>

Then, on your specific page (such asindex.htmlorarchive/detail.html), through{% extends %}Inherits tagsbase.html, and use{% block %}Label to cover or fill the corresponding area:

{% extends 'base.html' %} {# 声明继承自base.html,这必须是模板文件的第一行 #}

{% block title %}首页 - {% tdk with name="SiteName" %}{% endblock %} {# 覆盖title块 #}

{% block head_extra %}
    <link rel="stylesheet" href="{% system with name="TemplateUrl" %}/css/index.css">
{% endblock %}

{% block content %} {# 填充主内容区域 #}
    <section class="hero-section">
        <h1>欢迎来到我们的网站!</h1>
        <p>探索我们的最新内容。</p>
    </section>
    <!-- 其他首页特有的内容 -->
{% endblock %}

{% block footer_extra %}
    <script src="{% system with name="TemplateUrl" %}/js/index_analytics.js"></script>
{% endblock %}

Thus,index.htmlIt is automatically ownedbase.htmlThe header, navigation, and footer defined in it, while you only need to pay attention to its unique content part.

includevs.extendsWhen to choose?

In simple terms:

  • extendsUsed to define the overall pageLayout structure. If you need a universal page template that includes header, main content area, and footer sections, and most pages follow this structure, thenextendsIs preferred. It manages the "skeleton" of the page.
  • includeUsed to introduce components within the page.Independent componentsorcode snippets. When you need a small piece of content (such as a sidebar, advertisement, user comment area) to repeat in multiple places on a page that has already been structured, useincludeIt will be more efficient. It manages the "furniture" or "decoration" on the page.

A page will usually start withextendsa basic layout, then beingextendsin the basic layout coming in, or within the internal sub-templateblockarea, and then useincludeintroducing smaller public components

macroLabel (Advanced Usage Overview)

exceptincludeandextendsThe template engine of Anqi CMS also supportsmacroThe label is similar to a function in programming languages.

Related articles

How to define and use custom variables in a template?

In website operation, we often need to display diverse content, which may include system preset data, as well as customized personalized information based on business needs.AnQiCMS (AnQiCMS) fully understands this need, providing flexible and diverse mechanisms, allowing you to easily define and use custom variables in templates, thus achieving precise control and personalized display of content. This article will introduce you to the various methods of defining and using custom variables in AnQiCMS templates, helping you to fully utilize these features to create websites with more expressiveness and practicality.###

2025-11-09

How to implement automatic line break display for long text?

In website content operation, we often encounter situations where we need to display a large amount of text. If these long texts are not handled properly, they may exceed the designed container, causing chaos in page layout and severely affecting user experience.AnQi CMS provides us with flexible and powerful template functions, which can easily solve the display problem of long text, especially for automatic line breaks.### Core Strategy: Using the `wordwrap` filter to implement automatic text wrapping The template system of Anqi CMS is built-in with many practical filters (Filters), among which

2025-11-09

How to concatenate array elements into a string with a specified separator?

When operating a website, we often encounter the need to display a set of related data in the form of a list, such as multiple tags for articles, multiple keywords for product features, or multiple image URLs in an image library.At this time, if these scattered data elements can be integrated into a concise string and separated by specific symbols, it will greatly enhance the display effect and readability of the content.The Anqi CMS template engine provides a very practical `join` filter, which can easily meet this requirement.Understanding the `join` filter `join`

2025-11-09

How to split a string into an array with a specified separator?

In the daily operation of AnQi CMS, we often encounter the need to process some data stored as strings but actually containing multiple values.For example, an article may store multiple keywords in a comma-separated manner, or a custom content field may need to support multiple options, and these options are ultimately connected into a string with a specific symbol.In this case, we often need to split these strings using the preset delimiter into independent segments so that they can be displayed flexibly on the page or further processed.AnQi CMS based on the efficient architecture of Go language

2025-11-09

How to create reusable template code snippets (macros)?

In the daily content operation of Anqi CMS, we often encounter some interface elements or code structures that need to be used repeatedly.For example, a standardized article list item, a product display card with a unified style, or a footer contact information with specific layout information.If writing this code manually every time, it is not only inefficient but also prone to inconsistent formatting issues.This is where the "Macro" feature provided by Anqi CMS becomes particularly important, as it helps us easily create reusable template code snippets, greatly enhancing the efficiency and quality of template development.###

2025-11-09

How to design a basic template and allow other pages to inherit it?

Building websites in AnQi CMS, efficient and flexible template design is the key to improving development efficiency and maintaining website consistency.Among them, designing a basic template and allowing other pages to inherit it is the core strategy to achieve this goal.AnQi CMS adopts a syntax similar to the Django template engine, making template inheritance intuitive and powerful. ### Lay the Foundation: Create Your Basic Template First, let's create the basic template skeleton of a website. In Anqi CMS, all template files are stored in the `/template` directory

2025-11-09

How to display multi-language switch options for the current site?

How to easily add multilingual switching options to a website in AnQi CMS?With the continuous deepening of globalization trends, many enterprises and content operators find that having a website that supports multilingual is crucial for expanding the market and serving users in different regions.AnQi CMS understands this need, therefore it has built-in powerful multilingual support functions, allowing you to easily manage and display content in different languages. After your website content is prepared in multiple languages, the next step naturally is to provide visitors with an intuitive language switcher.This can not only improve the user experience

2025-11-09

How to add hreflang tags in templates to support multi-language SEO?

With the increasing trend of globalization, many websites are facing the challenge of providing content to users of different languages or regions.To ensure that your multilingual website performs well in search engines and accurately guides users to their preferred language version, adding the `hreflang` tag is crucial.AnQiCMS (AnQiCMS) is an enterprise-level content management system that deeply supports multilingualism and provides a convenient way to implement this feature in templates.### Understand the role of the hreflang tag `hreflang`

2025-11-09