How to use the `extends` tag in AnQiCMS templates to achieve template inheritance and content rewriting?

Calendar 👁️ 52

In the daily operation of Anqi CMS, we know that high-quality and clear website content is the key to attracting and retaining users.This is reflected not only in the words of the article, but also in the overall user experience and maintenance efficiency of the page.extendsTag to achieve template inheritance and content rewriting.

The core concept of template inheritance

When building a website, many pages share the same appearance and structure, such as headers, footers, sidebars, and unified layout frameworks.The traditional approach is to copy and paste this common code on every page, but this method brings a nightmare of maintenance - once the common part needs to be modified, all related files must be manually updated.

The template inheritance mechanism of AnQi CMS is exactly to solve this pain point.By defining a "basic template" (also known as a parent template), we place the common skeleton and default content of the website within it.Then, other "sub-templates" can inherit this base template and selectively "overwrite" or "fill" the reserved specific areas according to their own needs.extendsandblockThese tags play a core role

extendswithblockThe cornerstone of template inheritance

extendsThe tag is used to declare which parent template a child template will inherit.The function is like setting the gene source of a page, telling the Anqi CMS renderer that the structure and most of the content of the current template will come from the specified parent template.extendsThe tag must be the first tag in any sub-template, ensuring that the template parser can correctly identify its inheritance relationship.

AndblockThe tag is like a reserved 'slot' in the parent template. In the parent template, we use{% block block_name %}and{% endblock %}Define a reusable content area. This area can contain default content. When a sub-template inherits from a parent template and also defines a namedblockin the sub-template.blockThe content inside will completely replace the same namedblockdefault content. If the sub-template does not rewrite a certainblock, then the default content inside the parentblocktemplate will remain unchanged and be rendered.

Demonstration of practice: Building a base template that can be inherited

To better understand, we first create a namedbase.htmlThe basic template. This template will include the common structure of our website, such as document header information, main navigation, main content area, and footer.

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {# 页面标题区块,子模板可以重写 #}
    {% block title %}<title>安企CMS官网 - 轻松管理您的网站</title>{% endblock %}
    {# 额外头部内容区块,例如引入特有的CSS或JS #}
    {% block head_extra %}{% endblock %}
    <link rel="stylesheet" href="{% system with name="TemplateUrl" %}/css/main.css">
</head>
<body>
    {# 网站头部区块 #}
    {% block header %}
    <header class="site-header">
        <nav>
            <a href="/">
                <img src="{% system with name="SiteLogo" %}" alt="{% system with name="SiteName" %}" class="logo">
            </a>
            {% navList main_nav %}
            <ul>
                {% for item in main_nav %}
                <li class="{% if item.IsCurrent %}active{% endif %}">
                    <a href="{{ item.Link }}">{{ item.Title }}</a>
                </li>
                {% endfor %}
            </ul>
            {% endnavList %}
        </nav>
    </header>
    {% endblock %}

    <main class="container">
        {# 主要内容区块,所有子页面都会在此处填充其独特内容 #}
        {% block main_content %}
            <p>这里是默认的主要内容。</p>
        {% endblock %}
    </main>

    {# 网站页脚区块 #}
    {% block footer %}
    <footer class="site-footer">
        <p>{% system with name="SiteCopyright" %}</p>
        <p><a href="https://beian.miit.gov.cn/" rel="nofollow" target="_blank">{% system with name="SiteIcp" %}</a></p>
    </footer>
    {% endblock %}

    <script src="{% system with name="TemplateUrl" %}/js/main.js"></script>
    {# 额外底部JS区块,子模板可以引入特有JS #}
    {% block body_extra_js %}{% endblock %}
</body>
</html>

in thisbase.htmlin the file, we definedtitle/head_extra/header/main_content/footerandbody_extra_jsand many moreblock. TheseblockThis is the area reserved for content filling or rewriting for the sub-template.

Content rewriting: Create a sub-template and customize it

Now, we can create a namedindex.htmlsub-template to inherit frombase.htmlRewrite the content. For example, we want the homepage to have a unique title and display the latest article list in the main content area.

{% extends 'base.html' %}

{# 重写页面标题 #}
{% block title %}<title>首页 - 安企CMS,企业级内容管理首选</title>{% endblock %}

{# 重写主要内容区块,展示首页特有的内容 #}
{% block main_content %}
    <section class="hero-section">
        <h1>欢迎使用安企CMS</h1>
        <p>高效、可定制、易扩展的内容管理解决方案。</p>
        <a href="/about" class="btn btn-primary">了解更多</a>
    </section>

    <section class="latest-articles">
        <h2>最新文章</h2>
        <ul>
            {% archiveList archives with type="list" limit="5" moduleId="1" %}
            {% for item in archives %}
            <li>
                <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
                <p>{{ item.Description|truncatechars:100 }}</p>
                <span>发布日期: {{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
            </li>
            {% endfor %}
            {% empty %}
            <li>暂无文章发布。</li>
            {% endarchiveList %}
        </ul>
    </section>
{% endblock %}

{# 如果不需要重写 header 或 footer,它们将自动使用 base.html 中的默认内容 #}

in thisindex.htmlIn the sub-template, we{% extends 'base.html' %}Declared that it inherits frombase.html. Then, we rewrotetitleandmain_contenttwoblock. Please note,headerandfooterthe block inindex.htmlwas not defined, which means that Anqi CMS will automatically renderbase.htmlThis is the default content of these two blocks. This is the strength of template inheritance—it achieves code reuse and modular content management.

In this way, we can easily create various layouts and content pages without having to write a lot of common HTML code.This greatly improves the development efficiency of the template, reduces the complexity of later maintenance, and ensures the overall visual consistency of the website.

Frequently Asked Questions

extendsIs the tag supposed to be the first tag in the template file?

Yes,extendsThe tag must be the first tag in the sub-template file.This is the strict requirement of Anqi CMS template engine (as well as Django template engine), because it needs to know first which parent template the current template is inheriting in order to correctly parse and merge the content.extendsAny content before the tag, including HTML comments or blank lines, can cause the template inheritance feature to fail.

If the sub-template does not overwrite a certain one in the parent templateblockWhat will happen?

If a child template inherits a parent template but does not overwrite one defined in the parent templateblockthen the Anqicms rendering will automatically use the one defined in the parent templateblockThe default content inside. This means that even if the child template only overrides a few blocks, the other common parts of the website will still remain consistent.

extendsandincludeWhat are the main differences between tags?

extendsandincludeAll are used as reusable tags for templates, but their purposes and mechanisms are completely different.extendsThe implementation is "template inheritance", which means that the child template inherits the overall structure of the parent template and can optionally overwrite specific block content.It emphasizes the "is-a" relationship (a child template is a type of parent template).includeIt implements the "code snippet inclusion", which inserts an independent template file (typically a small, reusable UI component, such as a sidebar, navigation snippet, etc.) directly into the specified position of the current template.It emphasizes the "has-a" relationship (the current template includes some component).extendsIt defines the overall structure of the page, whileincludeis used to fill in specific small components within the structure.

Related articles

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, extracting common parts (such as navigation bars, footers, sidebars, etc.) and managing them independently, and introducing them to each page in a unified way, 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 effortless.AnQiCMS's template system is based on Go language and has borrowed from

2025-11-06

How to declare and assign variables in AnQiCMS templates for subsequent use?

As an experienced security CMS website operator, I am well aware of the importance of template design for website content display and user experience.Using variables in templates is the key to customizing pages and improving development efficiency.Today, I will elaborate on how to declare and assign variables in the AnQiCMS template, so that you can build and manage your website content more effectively.

2025-11-06

How to format a timestamp into a readable date and time in the AnQiCMS template?

As an experienced CMS website operation personnel of an enterprise, I know that every detail of user experience is crucial in content management.Clarity in presenting dates and times often directly affects readers' perception of the timeliness and professionalism of the content.Today, I will give a detailed explanation of how to convert those mysterious timestamps into the readable date and time format that we are accustomed to in the AnQiCMS template.

2025-11-06

How to generate a pagination navigation with page number control in AnQiCMS template?

Hello! As a senior CMS website operator, I fully understand the importance of high-quality content and user experience.Page navigation is an indispensable part of content-based websites, directly affecting the user's browsing experience and the discoverability of content.In AnQiCMS, generating a pagination navigation with page number control is an intuitive and powerful process. Below, I will elaborate on how to implement this feature in the AnQiCMS template.### In AnQiCMS template, generate pagination navigation with page number control In the content management system

2025-11-06

How to define and use macro functions to create reusable code blocks in AnQiCMS templates?

As an experienced security CMS website operation personnel, I am well aware that the template function of the content management system is crucial for improving website operation efficiency and content display quality.AnQiCMS's powerful Django template engine syntax provides us with flexible content presentation capabilities, and the Macro function feature is an essential tool for code reuse, simplifying template structure, and improving development and maintenance efficiency.During the process of content creation and publishing, we often encounter some repetitive code snippets, such as the display format of article lists and the layout of product cards

2025-11-06

How to cut, replace, or format strings in AnQiCMS templates?

As an experienced CMS website operation personnel in a safety company, I fully understand the importance of content in attracting and retaining users.A powerful and flexible template system that allows us to accurately present content according to different scenarios and user needs.AnQiCMS with its Django template engine syntax, provides us with rich string processing capabilities, whether it is for slicing, replacing, or formatting, it can be easily realized, thus transforming the original data into captivating web content.### AnQiCMS in template string variable acquisition and basic processing in

2025-11-06

How to ensure safe output of HTML content without escaping in AnQiCMS templates?

As an experienced website operator proficient in AnQiCMS, I am well aware of the importance of secure content output, while also ensuring the complete presentation of high-quality content.In AnQiCMS template development, dealing with HTML content often encounters a core issue: how to ensure that these HTML contents are rendered as expected and not escaped to plain text by the template engine?This not only involves the display effect of the content, but also concerns the security of the website.AnQiCMS uses a syntax similar to the Django template engine, one of its core design philosophies is security.This means

2025-11-06

How to judge if a variable is empty in AnQiCMS template and set a default value?

As a senior AnQi CMS website operation personnel, I know that handling variables with flexibility and robustness is crucial in template development and content display.Especially when the data source may be uncertain or missing, how to elegantly judge whether a variable is empty and provide a reasonable default value, which directly affects the user experience and the stability of page rendering.The AnQi CMS, with its template engine similar to Django, provides us with powerful and intuitive tools to meet these challenges.

2025-11-06