How to implement template inheritance with the `extends` tag and overwrite specific blocks of the parent template?

Calendar 👁️ 59

As an experienced website operations expert, I know that a flexible and efficient template system is crucial for the long-term development of a website.In AnQiCMS (AnQiCMS), it draws on the powerful capabilities of the Django template engine, allowing you to manage the website interface in a simple and logical way.extendsLabel, delve into how it implements template inheritance and allows us to accurately rewrite specific blocks of the parent template.

Template inheritance: Building the 'skeleton' and 'flesh' of a website.

Imagine your website as a meticulously designed building.The website's header, footer, sidebar, and overall layout, these are like the steel framework of a building, they remain consistent on the vast majority of pages.And each page's specific content area, such as article details, product display, contact us, etc., is like the decoration and functional zoning of the interior of a building, each with its own characteristics.

In traditional web development, if each page is written from scratch in HTML code, then once the framework needs to be modified (such as updating the navigation menu), you will have to adjust each file individually, which is undoubtedly a huge waste of efficiency and is also prone to errors.The template inheritance mechanism of AnQi CMS is exactly born to solve this pain point.

ByextendsLabel, you can define a "parent template" (also known as a "basic template"), which contains the common structure and layout of the website. In this parent template, you can use{% block %}Label some areas that can be filled or rewritten by sub-templates. TheseblockThese areas are like预留的 openings left on the skeleton, waiting for different sub-templates to inject their own 'flesh'.

For example, in yourbase.htmlparent template, you might define a general structure like this:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    {% block title %}
        <title>我的网站 - AnQiCMS</title>  {# 默认标题 #}
    {% endblock %}
    <link rel="stylesheet" href="{% system with name="TemplateUrl" %}/css/style.css">
    {# 其他公共头部元素 #}
</head>
<body>
    <header class="main-header">
        {# 网站通用导航栏等 #}
        {% include 'partial/header.html' %}
    </header>

    <div class="container">
        <aside class="sidebar">
            {# 通用侧边栏内容 #}
            {% include 'partial/aside.html' %}
        </aside>
        <main class="content-area">
            {% block content %}
                {# 父模板的默认内容,如果子模板不重写,则显示这里 #}
                <p>欢迎来到我的网站!</p>
            {% endblock %}
        </main>
    </div>

    <footer class="main-footer">
        {# 网站通用页脚信息 #}
        {% include 'partial/footer.html' %}
    </footer>
</body>
</html>

in thisbase.htmlIn it, we defined twoblock:titleandcontentThey each provide a default content. If any child template inheritsbase.htmlbut does not overwrite theseblockthen the default content of the parent template will be displayed.

Rewrite block: Customizing page personalization needs

When you need to create a specific page, such as the homepage or article detail page, you just need to create a new template file (such asindex.html),and use{% extends %}The tag declares it inherits frombase.html. It is worth noting that,{% extends %}The tag must be the first tag in the child template, this is a rule of the Anqi CMS template engine to ensure the clarity of the inheritance relationship.

Then, you canindex.htmlBy defining the same name in{% block %}tags to overwrite the specific area in the parent template. For example, to set a unique title and content for the homepage, yourindex.htmlmight look like this:

{% extends 'base.html' %}

{% block title %}
    <title>首页 - 我的定制内容</title> {# 重写了父模板的title #}
{% endblock %}

{% block content %}
    <section class="hero-banner">
        <h2>欢迎来到我们的首页!</h2>
        <p>这是安企CMS驱动的最新内容展示。</p>
    </section>
    <div class="latest-articles">
        <h3>最新文章</h3>
        {# 这里可以使用archiveList标签动态加载文章列表 #}
        {% archiveList archives with type="list" limit="5" %}
            <ul>
                {% for item in archives %}
                    <li><a href="{{item.Link}}">{{item.Title}}</a></li>
                {% endfor %}
            </ul>
        {% endarchiveList %}
    </div>
{% endblock %}

in thisindex.htmlIn the sub-template:

  1. {% extends 'base.html' %}Explicitly states that it will inheritbase.htmlAll structures and blocks not overwritten.
  2. {% block title %}Re-defined the page's<title>Tag content, overriding.base.htmlThe default title.
  3. {% block content %}It provides the unique content of the homepage, including a hero banner and a list of the latest articles, which will completely replacebase.htmlincontentThe default text of the block “Welcome to my website!”.

In this way, you can flexibly customize the unique content and layout for each page without touching the public skeleton of the website. When the public parts of the website (such as the header, footer) need to be updated, you only need to modifybase.htmlA file, all its child pages will be automatically updated, greatly improving the maintenance efficiency and consistency of website content management.

The operational value of template inheritance.

From the perspective of website operation, template inheritance brings many conveniences and advantages:

  • Improve maintenance efficiencyWhen the website structure or UI style needs to be adjusted, only the core parent template needs to be modified, without having to modify hundreds or even thousands of page files one by one, which greatly reduces maintenance costs and error rates.
  • Maintain brand consistencyThe public elements of the website (such as navigation, brand logo, footer information) are managed uniformly through the parent template, ensuring that the visual style and brand image of the entire website are highly consistent, enhancing the user's trust.
  • Optimize SEO performance: Although TDK (Title, Description, Keywords) can be used toblockCustomizing in the child template, but the overall structure, navigation links, and other common elements of the page are also important for SEO. Template inheritance ensures the consistency of these SEO-friendly elements.
  • Accelerate content iterationThe content operations team can quickly create new page types based on existing templates, focusing only on filling specific content blocks without worrying about the overall page structure.
  • Promote teamwork:Front-end developers can focus on building and maintaining basic templates, while content editors or specific page developers can quickly fill in and customize content on this basis, achieving separation of duties and improving collaboration efficiency.

In conclusion, in AnQi CMSextendsandblockTags are a key tool for managing efficient and flexible web interface.They perfectly separate the 'skeleton' and 'flesh' in website design, allowing you to enjoy a unified style while also freely customizing the unique features of each page.


Frequently Asked Questions (FAQ)

  1. extendsWhere must the tag be placed in the sub-template? extendsThe tag must be in the sub-template fileThe firstLabel.If there is any other HTML code, blank lines, or template tags before it, it will cause the template inheritance to fail.This is the strict specification of the AnQi CMS (and similar Django/Jinja2) template engine.

  2. 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 define or overwrite a certain{% block name %}area, then the parent template will have thatblockThe default content contained in the region will be displayed as is. This allows the parent template to provide generic fallback content, ensuring the integrity of the page.

  3. extendsandincludeWhat are the differences in usage scenarios for tags? extendsTags are used to implementTemplate inheritanceIt defines a "parent-child" relationship, where the child template inherits the overall structure (skeleton) of the parent template and can be customized to rewriteblockto customize specific areas. Andincludeused for labelinginserting code snippetsIt inserts an independent template file (usually a small, reusable component, such as a navigation bar, ad slot, etc.) directly into the specified position of the current template. It does not involve parent-child structure or area rewriting, but simply copies and pastes the code. In short, It isextendsIt is to build the overall framework,includeIt is to fill the local components.

Related articles

How to implement code reuse and pass additional variables using the `include` tag in template development?

As an experienced website operations expert, I am well aware of the importance of template development efficiency and code maintainability for a website in my daily work.AnQiCMS (AnQiCMS) relies on its efficient architecture based on the Go language and the Django-style template engine, providing us with powerful content management capabilities.Today, let's delve deeply into a tool that can significantly improve efficiency and code reuse in Anqi CMS template development, namely the `include` tag, especially how it helps us achieve code reuse and flexibly pass additional variables.

2025-11-06

How to use `with` or `set` tags to define and assign variables in AnQiCMS templates?

AnQiCMS's template system is known for its flexibility and ease of use, providing strong support for content operators and developers.In the presentation of content, we often need to define temporary variables to handle data, optimize logic, or pass parameters.AnQiCMS template engine borrowed the syntax style of Django templates and provided two very practical tags to help us achieve this goal: `with` and `set`.Understanding their respective features and application scenarios can make your template code clearer and more efficient.

2025-11-06

The `for` loop tag can iterate over arrays, but it also supports advanced usages like `reversed` or `empty`?

## The `for` loop in Anqi CMS template: Not just iteration, but advanced techniques to help you achieve twice the content operation results As a senior website operation expert, I am well aware of the importance of an efficient and flexible content management system for enterprises.AnQiCMS (AnQiCMS) leverages its high-performance architecture based on the Go language and Django template engine syntax to provide strong support for our content creation and display.In daily operations, we often need to present data collections in the form of lists on websites, at which time, the `for` loop traversal tag is undoubtedly our reliable helper

2025-11-06

Which conditional judgment operations does the `if` logical judgment tag support in the AnQiCMS template?

As an experienced website operation expert, I am well aware that a powerful and flexible template system is crucial for the effective presentation of website content.AnQiCMS (AnQi Content Management System) takes full advantage of its high efficiency based on the Go language and the grammar features borrowed from Django template engine, providing great convenience for our content operation.In AnQiCMS template development, proficiently using logical judgment tags is the key to achieving dynamic content display and enhancing user experience.Today, let's delve into the various conditional judgment operations supported by the `if` logical judgment tag in the AnQiCMS template

2025-11-06

How to define and call the `macro` macro function in the AnQiCMS template to create reusable code snippets?

In the process of website operation and development, we always encounter the need to repeatedly write similar code segments, such as unified article card styles, product information display modules, or form elements with specific interactions.If you start from scratch every time, it is not only inefficient, but also makes maintenance a nightmare.AnQi CMS is well-versed in this, its powerful template engine provides us with the 'macro' macro function, a tool aimed at helping developers and operators easily create reusable code snippets

2025-11-06

How to output system information configured in the AnQiCMS template, such as website name, Logo, and filing number?

In the flexible world of AnQiCMS, elegantly presenting the system-level information configured in the background to the front end of the website is a core skill that every website operator and template developer needs to master.As an experienced website operations expert, I know that these seemingly trivial details are invaluable for enhancing brand image, optimizing user experience, and meeting regulatory requirements (such as displaying the filing number).Today, let's delve deeply into how to output these valuable background information in the AnQiCMS template in a natural and smooth manner. AnQiCMS

2025-11-06

What is the core function of the `archiveParams` tag in AnQiCMS template?

In the world of AnQi CMS templates, efficiently and flexibly displaying content is the key to the success of website operation.We know that a good content management system not only needs to manage standardized information but also needs to adapt to the ever-changing business needs and provide personalized content display.Today, let's delve deeply into a crucial tag in the AnQiCMS template, `archiveParams`, which is the幕后 hero behind highly customized content.What is the core function of the `archiveParams` tag in AnQiCMS templates?

2025-11-06

How to use the `archiveParams` tag to display all custom parameters of the current document in AnQiCMS template?

AnQiCMS template's `archiveParams` tag: easily display all custom parameters of the document As a senior website operations expert, I am well aware that in a content management system, how to flexibly display and utilize the various properties of documents is crucial for website customization and functional expansion. AnQiCMS, as an efficient and customizable content management system, provides a rich and powerful set of template tags, among which the `archiveParams` tag is the core tool to unlock the powerful features of document custom parameters.

2025-11-06