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

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,