How does AnQiCMS template reference other template files (such as `header.html`, `footer.html`) to achieve code reuse?

Calendar 👁️ 73

In website construction and maintenance, how to efficiently manage code and avoid redundant work is the key to improving development efficiency and ensuring website consistency.For users who build websites using AnQiCMS, its flexible template engine provides a powerful code reuse mechanism, allowing us to easily refer to other template files, such as the common header (header) and footer (footer), thus achieving modular development.

The template design of AnQiCMS draws on the syntax features of the Django template engine, which makes it very easy for developers familiar with frontend development or those who have encountered other mainstream CMS templates to get started.The core idea is that you can extract the repeated parts in the website as independent template files and then reference them where needed.This not only reduces the amount of code, but more importantly, when these common parts need to be modified, you only need to change one file to take effect throughout the site, greatly enhancing the maintainability and consistency of the website.

includeLabel: Flexible Code Fragment Embedding

In the AnQiCMS template, the most direct and commonly used method of code reuse is to useincludeThe tag is used to embed the content of a template file directly into a specified location in another template file.It is very suitable for handling those relatively independent, self-contained page elements, such as the navigation bar of a website, (header.html)、Bottom Information Area(footer.htmlSide panel (sidebar.html), even components that appear repeatedly on a page (such as article list items, product cards, etc.).

UseincludeThe label is very intuitive, you just need to specify the path of the template file to be included in the main template file. For example, suppose there is apartialfolder, containing theheader.htmlandfooter.html:

<!-- template/your_template_name/index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>我的 AnQiCMS 网站</title>
</head>
<body>
    {% include "partial/header.html" %}

    <main>
        <h1>欢迎来到我的网站</h1>
        <p>这是网站的主体内容。</p>
    </main>

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

Here, {% include "partial/header.html" %}and{% include "partial/footer.html" %}Willpartial/header.htmlandpartial/footer.htmlInsert all content without any changes.index.htmlat the corresponding position.

includeThe tag also provides more flexible usage. If you are not sure whether a file definitely exists, you can useif_existsThe parameter, so even if the file does not exist, the page will not report an error, but silently ignore the reference:

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

Sometimes, you may want to pass some specific data to the template file being included. In this case, you can usewithkeywords to specify variables:

<!-- partial/header.html 中可以接收 title 和 keywords 变量 -->
<header>
    <nav>
        <h1>{{ title }}</h1>
        <p>关键词:{{ keywords }}</p>
        <!-- 其他导航内容 -->
    </nav>
</header>

<!-- 在主模板中这样引用并传递变量 -->
{% include "partial/header.html" with title="AnQiCMS 官方网站" keywords="AnQiCMS, 建站, CMS" %}

If you only want the template file included to use the variables you explicitly pass, and not inherit all the context variables of the current main template, you can useonlyKeyword:

{% include "partial/header.html" with title="AnQiCMS 官方网站" only %}

Thus,partial/header.htmlonly access totitleVariables, while unable to access other variables in the main template.

extendsandblock: Build the website skeleton

When we need to define the overall layout of the website, for example, all pages share the same<head>Area, top navigation, bottom copyright information, but the main content (articles, product details, lists, etc.) is different when,extendsandblockThe combination of labels is particularly powerful. This is a mechanism of template inheritance, which allows you to create a "skeleton" template, and then other page templates can "inherit" this skeleton and only fill in or modify the specific areas reserved in the skeleton.

First, you need to create a basic layout template, usually namedbase.htmlorlayout.html. In this template, define the common structure of the website and useblockLabel those areas that may be overridden in sub-templates:

<!-- template/your_template_name/base.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}AnQiCMS 网站{% endblock %}</title>
    <link rel="stylesheet" href="{% system with name='TemplateUrl' %}/css/style.css">
    <!-- 其他公共样式和脚本 -->
</head>
<body>
    {% include "partial/header.html" %} {# 顶部导航,可以继续使用 include #}

    <div id="wrapper">
        {% block content %}
            <!-- 子模板将在这里填充具体内容 -->
        {% endblock %}
    </div>

    {% include "partial/footer.html" %} {# 底部信息,也可以继续使用 include #}
    <script src="{% system with name='TemplateUrl' %}/js/main.js"></script>
</body>
</html>

Inbase.htmlIn it, we defined twoblockArea:titleandcontentNow, any other page template that wants to use this layout just needs to use it at the beginning of the file.extendsInherit it through the sameblockFill or override the tagbase.htmlThe content corresponding to the

<!-- template/your_template_name/index.html (或其他页面,如 detail.html, list.html) -->
{% extends "base.html" %} {# 声明继承 base.html,这必须是模板文件的第一行 #}

{% block title %}网站首页 - {% system with name='SiteName' %}{% endblock %}

{% block content %}
    <section class="hero">
        <h2>欢迎使用 AnQiCMS 构建您的网站</h2>
        <p>轻松管理内容,高效展示信息。</p>
    </section>

    <section class="features">
        <h3>核心功能</h3>
        <ul>
            <li>多站点管理</li>
            <li>灵活内容模型</li>
            <li>高级 SEO 工具</li>
        </ul>
    </section>
{% endblock %}

Thus,index.htmlThere is no need to rewrite<head>/<body>/header/footerPublic code, just focus ontitleandcontentThe specific content of the region is enough. The overall structure of the page is controlled bybase.htmlunified, while the specific content of each page is responsible by the sub-template

Template file organization:partial/the directory convention

To better organize and manage these reusable template files, the AnQiCMS template guide suggests that small, reusable code snippets (such as sidebars, breadcrumb navigation, footers, etc.) can be stored inpartial/In the directory. For example:

/template
  /your_template_name
    /partial
      header.html
      footer.html
      sidebar.html
      breadcrumb.html
    base.html
    index.html
    article_detail.html
    ...

This structure clearly defines the responsibilities of the template:base.htmlDefines the overall layout of the website,index.htmlorarticle_detail.htmlWhile the specific page templates are,partial/Files under the directory are various widgets and public areas.

Through the two main code reuse mechanisms mentioned above -includeTags are used to embed independent segments,extendsandblockTags used to build and fill the page skeleton - AnQiCMS makes website template development efficient and easy to maintain.You can say goodbye to tedious copy and paste, focus on the creativity and design of website content, and let the technical tools truly serve the goal of content operation.


Frequently Asked Questions (FAQ)

1. When should I useincludeWhen to useextendsandblock?Generally speaking,extendsandblockIt is suitable for building the overall structure and layout of a page (such as the header, footer, and sidebar framework of a website), because they define a parent-child relationship, where child templates inherit the overall structure of the parent template and modify specific areas. AndincludeTags are more suitable for embedding small code snippets that are relatively independent and can be reused on different pages or in different areas, such as a specific menu item in a navigation bar, an ad slot, an article summary card, or a general form

Related articles

How to define and use temporary variables in AnQiCMS templates to simplify complex data processing?

In AnQiCMS template development, we often encounter situations where we need to process or reuse complex data.Writing complex logic or data paths repeatedly in templates not only makes the code long and hard to read, but also affects maintenance efficiency.At this time, skillfully using temporary variables can make template code clearer and more concise, as well as more flexible in data processing.AnQiCMS's template engine provides a powerful and flexible variable definition mechanism that can help us effectively manage and process page data.

2025-11-07

How to iterate over an array or object list in AnQiCMS template and display loop count and remaining quantity?

In website content management, dynamically displaying list data is a basic and crucial function.Whether it is an article list, product display, or user comments, we need to present the data efficiently to the users.How to clearly mark the order of list items or inform the user how much content is left to browse can greatly enhance the user experience and readability of the content.AnQiCMS (AnQiCMS) with its flexible template engine, can help us easily meet these needs.

2025-11-07

How to display or hide content blocks in AnQiCMS templates based on conditions (such as `if` statements)?

In website content operation, we often need to display or hide specific content based on different situations, such as displaying special event information on holidays or showing different operation buttons based on the user's status.AnQiCMS provides a flexible template engine, allowing you to easily implement these dynamic content controls, with the most core tool being the conditional statement - `if`. AnQiCMS template syntax is similar to the popular Django template engine, and it is very easy to get started with.

2025-11-07

How to get and display detailed information of a specific user, such as username, avatar, and level in AnQiCMS template?

In website operation, displaying personalized information to users, such as usernames, avatars, and membership levels, can greatly enhance user experience and website interaction.AnQiCMS as a flexible content management system provides intuitive template tags to help us easily achieve this goal.The AnQiCMS template system has adopted a syntax similar to Django templates, allowing backend data to be called through concise tags.When we want to display detailed information about a specific user

2025-11-07

How to display Markdown formatted article content in AnQiCMS template and render it correctly to HTML?

In a content management system, Markdown has become the preferred writing format for many content creators, it is concise, efficient, and easy to convert to structured HTML.For AnQiCMS users, using Markdown to write articles can not only improve writing efficiency but also better organize content structure.Luckyly, AnQiCMS deeply supports Markdown formatted article content and provides a perfect mechanism to ensure that they are correctly rendered into beautiful HTML pages on the website front-end.### Start

2025-11-07

How to implement the parameter filtering function of the article list in AnQiCMS (such as filtering by custom properties)?

As the content of the website becomes richer, users often hope to find the information they are interested in more accurately, rather than searching for a needle in a haystack of disordered content.For operators, providing flexible article list filtering functions can not only significantly improve user experience but also effectively help users discover more related content, thereby increasing the time spent on the website and interaction.AnQiCMS fully understands this need, through its highly flexible content model and powerful template tag system, making it extremely simple and intuitive to implement the parameter filtering function for the article list.Even if it is a custom attribute

2025-11-07

How to display the comment list of articles in AnQiCMS template and support pagination?

Display article comment list and pagination elegantly in AnQiCMS template Article comments are an important part of website interaction, not only can they enhance user engagement, but also bring richer discussions and value to the website content.For operators, how to clearly and efficiently display these comments on the page and support pagination is the key to improving user experience.AnQiCMS provides a set of intuitive and powerful template tags, allowing you to easily achieve this goal.### Understand AnQiCMS template basics AnQiCMS uses similar

2025-11-07

How to integrate the message form into the AnQiCMS template and dynamically display the custom form fields configured in the backend?

In today's digital world, websites are not just platforms for displaying information, but also important bridges for interaction and communication with users.A well-designed, feature-complete feedback form that can greatly enhance user experience, help websites collect feedback, and gain business opportunities.AnQiCMS (AnQiCMS) is well-versed in this, providing powerful message form integration capabilities. Particularly impressive is that it allows us to flexibly configure custom form fields through the backend and dynamically present these fields in the frontend template, thereby meeting various personalized business needs

2025-11-07