How to overwrite a specific content area or `block` in a child template inheriting from a parent template?

Calendar 👁️ 76

Advanced AnQi CMS template: Flexibly rewrite the specific content area of the parent template

As an experienced website operations expert, I am well aware of the importance of a flexible and efficient content management system for enterprise operations.AnQiCMS (AnQiCMS) provides us with great convenience with its high-performance architecture based on the Go language and the Django-style template engine.In daily content operations, we often need to maintain a unified style of the website, but at specific pages, there is a need for different local content.At this point, it is particularly important to master how to overwrite specific content areas in child templates that inherit from parent templates.

The Anqi CMS template system is designed to be very intuitive, drawing on many excellent ideas from modern front-end frameworks, especially its support for template inheritance, allowing us to build websites like building blocks. The core of this mechanism lies in two tags:{% extends %}and{% block %}.

Understand the template inheritance mechanism of Anqi CMS

Imagine that your website has a common 'skeleton' - something that includes the header, footer, navigation bar, and some common styles.These are more or less the same on every page of the website. However, the core content areas of the article details, product displays, or independent pages all have their own characteristics.If each page is written from scratch, it is undoubtedly a huge amount of work and difficult to maintain.

This is when template inheritance comes into play.We can create a "parent template" (or "master template"), which defines the overall layout and common elements of all web pages.{% block 名称 %}{% endblock %}Tags are used to mark the areas that may need to be rewritten or filled by child templates in the future. TheseblockIt is like a reserved "slot", waiting for a sub-template to "insert" its content.

While the "sub-template" goes through{% extends '父模板文件名' %}The tag declares which parent template's layout it will inherit. Once the inheritance relationship is established, the child template can optionally overwrite anyblock. If the child template does not overwrite a specificblock, it will automatically inherit the parent template of theblockDefault content. This design pattern greatly enhances the reusability and maintainability of the template.

How to rewrite a specific content area in a sub-template?

The template files of AnQi CMS are usually stored in/templatethe directory, and.htmlAs a suffix. Let's delve deeper into rewriting through a concrete exampleblocksteps.

First step: Define your parent template (for examplebase.html)

Firstly, we need to define the areas that can be overwritten in the parent template. These areas are wrapped using{% block 名称 %}and{% endblock %}tags. For example, a typicalbase.htmlmight look like this:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {%- tdk seoTitle with name="Title" siteName=true %}
    <title>{{ seoTitle }}</title> {# 定义一个名为 title 的 block,并设置默认内容 #}
    {%- endtdk %}
    <link rel="stylesheet" href="{% system with name="TemplateUrl" %}/css/main.css">
    {% block extra_head %}{% endblock %} {# 定义一个用于添加额外CSS或JS的 block #}
</head>
<body>
    <header>
        {% block header %}
            <nav>这是网站的通用导航</nav>
        {% endblock %} {# 通用页头导航区域 #}
    </header>

    <main>
        <aside>
            {% block sidebar %}
                <p>这是默认的侧边栏内容。</p>
            {% endblock %} {# 侧边栏区域 #}
        </aside>
        <section>
            {% block content %}
                <h1>欢迎访问安企CMS!</h1>
                <p>这是父模板中默认的主体内容。</p>
            {% endblock %} {# 核心内容区域 #}
        </section>
    </main>

    <footer>
        {% block footer %}
            <p>&copy; {% now "2006" %} {% system with name="SiteName" %}. All Rights Reserved.</p>
        {% endblock %} {# 通用页脚区域 #}
    </footer>

    <script src="{% system with name="TemplateUrl" %}/js/main.js"></script>
    {% block extra_body_scripts %}{% endblock %} {# 定义一个用于添加额外JS的 block #}
</body>
</html>

in thisbase.htmlIn it, we definedtitle/extra_head/header/sidebar/content/footerandextra_body_scriptsand many moreblock. Eachblockthe inside always contains its default content.

Second step: Create a child template and inherit the parent template (for examplearticle_detail.html)

Now, let's assume we want to create a template for an article detail pagearticle_detail.html. This page needs to inheritbase.htmlthe overall layout, but needs to be rewrittentitleandcontentArea, andextra_headAdd some unique styles of the article.

Inarticle_detail.htmlAt the top of the file, use{% extends %}Declaration of inheritance relationship with the

{% extends 'base.html' %}

{# 这里是重写 title block #}
{% block title %}
    {% archiveDetail with name="SeoTitle" siteName=true %} {# 使用文章详情的SEO标题 #}
{% endblock %}

{# 这里是在 extra_head block 中添加内容 #}
{% block extra_head %}
    <link rel="stylesheet" href="{% system with name="TemplateUrl" %}/css/article.css">
    <style>
        .article-content img { max-width: 100%; height: auto; }
    </style>
{% endblock %}

{# 重写 content block #}
{% block content %}
    <article class="article-content">
        <h1>{% archiveDetail with name="Title" %}</h1>
        <p class="meta">
            <span>分类:<a href="{% categoryDetail with name='Link' %}">{% categoryDetail with name='Title' %}</a></span>
            <span>发布日期:{% archiveDetail with name="CreatedTime" format="2006-01-02" %}</span>
            <span>浏览量:{% archiveDetail with name="Views" %}</span>
        </p>
        <div>
            {%- archiveDetail articleContent with name="Content" %}
            {{articleContent|safe}} {# 文章内容,注意使用 |safe 过滤器避免HTML转义 #}
        </div>
        <div class="tags">
            {% tagList tags with limit="10" %}
            {% for item in tags %}
            <a href="{{item.Link}}">{{item.Title}}</a>
            {% endfor %}
            {% endtagList %}
        </div>
    </article>

    {# 这里我们还可以在侧边栏(sidebar)中显示相关文章 #}
    {% block sidebar %}
        <h3>相关文章</h3>
        <ul>
            {% archiveList archives with type="related" limit="5" %}
            {% for item in archives %}
            <li><a href="{{item.Link}}">{{item.Title}}</a></li>
            {% endfor %}
            {% endarchiveList %}
        </ul>
    {% endblock %}
{% endblock %}

{# 如果我们想在页脚的默认内容基础上,额外添加一些JS代码,可以使用 {{ block.super }} #}
{% block extra_body_scripts %}
    {{ block.super }} {# 保留父模板中 extra_body_scripts block 的所有内容 #}
    <script>
        // 文章详情页特有的交互JS
        console.log("文章详情页的自定义脚本已加载。");
    </script>
{% endblock %}

in thisarticle_detail.htmlIn the child template, we successfully rewrittentitleandcontent blockFill it with the SEO title and specific content of the article. Inextra_head blockWe added the CSS file and inline styles unique to the article detail page. It is noteworthy that,extra_body_scriptsThisblockWe used,{{ block.super }}This means it will render the parent template first,blockThe content is then appended after which we define new content in our sub-template. This is a very practical technique that achieves content stacking rather than complete replacement.

At the same time, we are alsocontentThis bigblockRewritten inside againsidebar blockThis showcases the ability to rewrite nested content, allowing the sidebar to display recommended content related to the current article, which is more tailored to the scenario of the article detail page.

In this way, we not only maintained the overall layout consistency of the website, but also赋予了 each page the ability to display unique content, realizing high customization and flexibility.

Operational tips and **practice

  • Clear namingFor yourblockGive a clear, descriptive name, such asmain_content/page_title/footer_linksThis will greatly improve the readability and collaboration efficiency of the template.
  • Appropriate granularityDo not split the entire page into small piecesblock,

Related articles

The `extends` tag must be placed at which position in the template file to work and parse correctly?

AnQiCMS (AnQiCMS) is an enterprise-level content management system developed based on the Go language, which provides strong support for content operations with its efficient and flexible features.In the process of template development, proficiently using its built-in Django style template engine is the key to improving efficiency.The `extends` tag is a powerful tool for implementing template inheritance and building a unified website layout.However, for this powerful feature to work properly and be correctly parsed by the template engine, its placement has strict conventions.

2025-11-07

In AnQi CMS template, how to create a basic layout skeleton (master template) for all pages to inherit?

## Advanced AnQi CMS Template: The Art and Practice of Building an Inheritable Basic Layout Skeleton (Master Page) Efficiency and consistency are two core elements in the daily operation of website management.Imagine if every page of a website needed to be individually designed and maintained for navigation bars, footers, and header Meta information, it would be a time-consuming and error-prone task.This is one of the problems that excellent content management systems like AnQiCMS (AnQiCMS) are committed to solving.

2025-11-07

The `macro` tag provides what conveniences in template debugging and error troubleshooting?

## Debugging and Troubleshooting of AnQi CMS Templates: The Unsung Hero of `macro` Tags In the fast-paced digital age, the stable operation and efficient iteration of websites are the foundation of operational success.AnQi CMS is an enterprise-level content management system developed based on the Go language, with its high performance, high concurrency features, and flexible template system, providing solid technical support for small and medium-sized enterprises and content operators.However, even the most powerful system is bound to encounter some tricky debugging problems during the development and maintenance of actual templates. Today

2025-11-07

`macro` tag definition code snippet can include other built-in template tags of Anqi CMS?

As an experienced website operations expert, I fully understand the importance of a powerful and flexible content management system (CMS) for a corporate website.AnQiCMS (AnQiCMS) leverages its high-performance architecture based on the Go language and the Django template engine syntax, providing great convenience for content operation.In daily content management and website maintenance, we often use built-in template tags to build dynamic pages.

2025-11-07

What role does the `block` tag play in template inheritance, when is its default content displayed, and when is it overridden?

In the daily operation of enterprise-level websites, efficient and flexible content management is the key to success.AnQiCMS (AnQiCMS) is a modern content management system developed based on the Go language, which brings great convenience to the customization of website development and content presentation with its support for Django template engine syntax.Today, let's delve deeply into one of the core elements of its template system - the `block` tag, and see how it plays a role in template inheritance, as well as when its content is displayed by default and when it is overridden by the child template.###

2025-11-07

If the child template does not overwrite a certain `block` content of the parent template, how will the page display?

## How will the page be displayed when the child template does not overwrite the parent template's Block?As an experienced website operation expert, I am well aware of the importance of a flexible and efficient content management system for enterprises and self-media.AnQiCMS (AnQiCMS) provides us with great convenience with its powerful architecture based on the Go language and syntax similar to the Django template engine.In daily content operation and website maintenance, the reusability of templates is the key to improving efficiency.where, the template inheritance mechanism

2025-11-07

How does the `extends` tag help the website maintain a consistent visual style and layout?

## The Secret to Website Style Consistency: Deep Analysis of the `extends` Tag in AnQi CMS In today's rapidly changing digital world, the visual style and layout consistency of a website is not only about aesthetics, but also about brand image, user experience, and even operational efficiency.Imagine if each page of your website had a different header, navigation, and footer, users would feel confused and unprofessional while browsing, and the brand image would suffer a big discount.AnQi CMS, this is an enterprise-level content management system developed based on the Go language, deeply understanding this field

2025-11-07

How `extends` tag achieves layout differentiation when designing pages for different content types (such as article details, product details)?

## Unlock AnQiCMS Layout Cube: How the `extends` tag implements differentiated design of content pages As an experienced website operations expert, I know that the way website content is presented is crucial for user experience and brand image.In a website filled with various types of content, how can one maintain a unified style while also allowing different types of content (such as in-depth articles, product introductions, event details) to have distinctive display pages, which is undoubtedly a challenge faced by many operators.In AnQiCMS (AnQiCMS), the core template inheritance mechanism

2025-11-07