How to implement template inheritance using the extends tag in AnqiCMS templates to unify the visual style of the website?

Calendar 👁️ 64

In website operation, maintaining a consistent visual style is the key to brand image and user experience.Imagine if every page layout on your website were different, with navigation positions changing back and forth, users would feel confused and even lose interest.extends.

AnqiCMS uses a template engine syntax similar to Django, which makes template development intuitive and efficient.extendsThe tag is the core of this mechanism, which can help you easily achieve a unified style for your website while maintaining flexibility.

Understanding the core value of template inheritance.

Why is template inheritance so important? We can understand its advantages from the following aspects:

  1. Unified visual styleYour website may have hundreds or even thousands of pages, each containing common areas such as headers, footers, and navigation bars.If this common area code is scattered across each template file, once you need to modify it (such as replacing the Logo, adjusting the navigation menu), you will have to modify all files one by one, which is undoubtedly a huge amount of work.By template inheritance, you can define these common elements in a "base template", which all pages inherit to ensure the consistency of the site's style.
  2. Enhance development efficiency: Do not rewrite the same code repeatedly. Just define it once, and it can be reused on all related pages. This greatly reduces development time, allowing you to focus more on customizing page content.
  3. Reduce maintenance costsWhen the website design needs to be updated, or a Bug occurs, you only need to modify one piece of code in the basic template, and all pages inheriting it will be automatically synchronized for updates, greatly simplifying maintenance work.This conforms to the design philosophy of AnqiCMS, which is 'efficient, customizable, and easy to expand'.
  4. Enhance content flexibility: It is important to maintain a unified style, but some special pages (such as event special pages, contact us pages) may require unique layouts or features.Template inheritance allows child templates to locally override or extend the content of parent templates without affecting the overall structure, thus achieving flexible page customization.

extendsHow do tags make magic happen?

AnqiCMS's template inheritance mechanism revolves around the 'basic template' and 'child template'.

1. Basic Template: The skeleton of the website

Firstly, you need to create a basic template file, usually namedbase.html, placed in your template root directory (for example/template/default/Below.This file is like the skeleton of your website, containing all the common structures and elements that should be present on all pages, such as the HTML header information, the header, the main navigation, and the footer.

In the base template, you need to useblocktags to define those areas that can be filled or overridden by child templates. Theseblocktags will have a unique name.

base.htmlExample:

<!DOCTYPE html>
<html lang="{% system with name='Language' %}">
<head>
    <meta charset="UTF-8">
    {# 定义一个可被子模板覆盖的标题区域 #}
    {% block title %}
        <title>{% tdk with name="Title" siteName=true %}</title>
    {% endblock %}
    <meta name="keywords" content="{% tdk with name="Keywords" %}">
    <meta name="description" content="{% tdk with name="Description" %}">
    <link rel="stylesheet" href="{% system with name="TemplateUrl" %}/css/style.css">
    {# 其他公共样式或脚本 #}
</head>
<body>
    <header class="main-header">
        <div class="logo">
            <a href="{% system with name="BaseUrl" %}"><img src="{% system with name="SiteLogo" %}" alt="{% system with name="SiteName" %}"></a>
        </div>
        <nav class="main-nav">
            {% navList navs %}
                <ul>
                    {% for item in navs %}
                        <li class="{% if item.IsCurrent %}active{% endif %}">
                            <a href="{{ item.Link }}">{{item.Title}}</a>
                            {# 如果有二级导航,这里可以继续嵌套 #}
                        </li>
                    {% endfor %}
                </ul>
            {% endnavList %}
        </nav>
    </header>

    <div class="container">
        {# 定义一个主内容区域,子模板将在这里填充各自的独特内容 #}
        {% block content %}
            <p>这是默认内容,如果子模板不定义,就会显示这里。</p>
        {% endblock %}
    </div>

    <footer class="main-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>
    <script src="{% system with name="TemplateUrl" %}/js/main.js"></script>
    {# 其他公共脚本 #}
</body>
</html>

2. Sub-template: Filling and Customization

Next, you can create the actual page template, such asindex.html(Home page),article/detail.html(Article detail page) orpage/about.html(About us page), and let them inheritbase.html.

To implement inheritance, you need to in the sub-templatethe first lineUse{% extends 'path/to/base.html' %}tag. The path here is relative to the template root directory. For example, ifbase.htmlin the template root directory, then it is{% extends 'base.html' %}.

In the sub-template, you can overwrite (or fill in) the definitions made in the base template.blockArea. As long as you define the same-named tags in the sub-template,blockthe content of which will replace the corresponding content in the base template.blockThe content.

index.htmlExample:

{% extends 'base.html' %} {# 必须是文件中的第一行 #}

{% block title %}
    <title>AnqiCMS 首页 - 快速搭建您的企业网站</title> {# 覆盖 base.html 中的 title block #}
{% endblock %}

{% block content %}
    <main class="homepage-content">
        <h1>欢迎来到我们的网站!</h1>
        <p>这里是 AnqiCMS 首页的独特内容。我们致力于提供高效、安全的内容管理解决方案。</p>

        <section class="latest-articles">
            <h2>最新文章</h2>
            {% archiveList archives with type="list" moduleId="1" limit="5" %}
                <ul>
                    {% for item in archives %}
                        <li><a href="{{ item.Link }}">{{ item.Title }}</a> - {{ stampToDate(item.CreatedTime, "2006-01-02") }}</li>
                    {% endfor %}
                </ul>
            {% endarchiveList %}
        </section>

        <section class="featured-products">
            <h2>推荐产品</h2>
            {% archiveList products with type="list" moduleId="2" limit="3" flag="c" %}
                <div class="product-grid">
                    {% for item in products %}
                        <div class="product-item">
                            <a href="{{ item.Link }}">
                                <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
                                <h3>{{ item.Title }}</h3>
                            </a>
                        </div>
                    {% endfor %}
                </div>
            {% endarchiveList %}
        </section>
    </main>
{% endblock %}

Magnificent{{ block.super }}

Sometimes, you may not want to completely replace the parent template inblockThe content, but rather add something on top of it. At this point,{{ block.super }}it comes into play. In the child template'sblockUse it to include the corresponding parent templateblockThe content.

For example, do you want to add some page-specific descriptions after the default title in the base template:

{% extends 'base.html' %}

{% block title %}
    {{ block.super }} - 文章详情
{% endblock %}

{# ... 其他内容 ... #}

In this way, the final<title>The tag will include the title of the parent template and “- Article Details”.

Little tricks in practice

  • Reasonable division of blocks: In designbase.htmlDon't put all the content in oneblockHere. It should be divided according to logical functions (such asblock header_nav/block sidebar/block main_content/block scriptsetc.) for detailed division. In this way, the sub-template can be customized more accurately for specific parts
  • Make good use ofincludeTag: For some that are in multipleblockOr the "code snippet" that is repeatedly used in different sub-templates (such as a user login form, a social sharing button group), you can use{% include "partial/login_form.html" %}Introducing in this way. This can further improve the reusability of the code. AnqiCMS template system also perfectly supports this nesting.
  • Clear block name: GiveblockName a tag with a meaningful name that can help you quickly locate and understand the role of each block in a complex template structure.
  • Static Resource Management: AnqiCMS约定模板的样式、JS、images等静态资源存放在/public/static/目录。在模板中引用时,可以使用{% system with name="TemplateUrl" %}Label to get the static file address of the current template, ensure the path is correct and flexible.

Achieve the perfect combination of unified style and flexible customization.

ByextendsTags andblockMechanism, you can easily implement it in AnqiCMS:

  • **Consistent header across the entire site

Related articles

How to use AnqiCMS template include tag to introduce common code fragments and achieve page structure reuse?

In website content management, we often encounter situations where it is necessary to display the same content blocks, such as headers, footers, sidebars, or navigation menus, on multiple pages.If you copy and paste this code every time, it is not only inefficient, but also when you need to modify it, you have to face the繁琐 of repeated operations in multiple files.If this continues, the maintenance and updates of the website content will become extremely difficult, and inconsistencies in the experience may even occur.

2025-11-09

How to use with or set tags in AnqiCMS templates to define variables for optimizing content display and maintenance?

In AnqiCMS template development, defining and using variables are indispensable skills to make our website content more flexible and code easier to maintain.The system uses a syntax similar to the Django template engine, where `with` and `set` tags are used to define variables, optimizing content display and managing templates effectively.Understanding and using them effectively can make your website operation twice as effective.Why do we need to define variables in the template?

2025-11-09

How to format a timestamp in AnqiCMS template to display a custom date and time format?

In AnqiCMS, managing website content, we often need to display the publication time, update time, or registration and login time of users, etc.These time information is usually stored in the database in the form of a timestamp, which is a series of numbers.If displayed directly on the website front end, these numbers are not intuitive and lack aesthetics.Fortunately, AnqiCMS provides very flexible template tags, allowing us to easily format these timestamps into the date and time display format we want.AnqiCMS template system

2025-11-09

How to iterate through data using the for loop tag in AnqiCMS templates and display list content on the front end?

In modern website construction, content lists are everywhere, whether it is article lists, product displays, user comments, or navigation menus, they cannot do without efficient organization and presentation of data.AnqiCMS as an enterprise-level content management system based on Go language, provides intuitive and powerful loop tags in template creation, allowing you to easily display various list content on the front page.

2025-11-09

How does AnqiCMS ensure that mathematical formulas and flowcharts can be displayed correctly on the front end after enabling the Markdown editor?

Today, with the increasing diversity of content creation, websites not only carry text and images, but also often need to display complex mathematical formulas or intuitive flowcharts.For those who use AnqiCMS, the good news is that the system has built-in powerful Markdown editor support, and with simple configuration, it can ensure that these professional contents are perfectly presented on the website front-end.Below, let's take a look at how to operate, making your website content richer and more professional.

2025-11-09

How to correctly display the independent content of each site on the front page of the multi-site management function of AnqiCMS?

In today's digital environment, many businesses and individuals need to manage multiple websites, whether it be different brand sites, product sub-sites, or multilingual versions for different markets.A system that can efficiently handle content across multiple sites is particularly important to meet such demands.The multi-site management feature of AnqiCMS is exactly for this purpose, it allows you to easily manage multiple websites from a single backend, while ensuring that each site can independently and correctly display its exclusive content on the front page.### The core advantages of AnqiCMS multi-site management First, let's understand

2025-11-09

How to display friendly information to users on the front end during the website maintenance period of AnqiCMS's 'Shutdown Prompt' feature?

In website operations, we all understand the importance of maintenance work.Whether it is system upgrade, data migration, or solving emergency faults, the website will always have a period of time when it has to be "offline".However, how to ensure the smooth progress of maintenance work during this special period, while minimizing the impact on user experience and not damaging the professional image of the website, this is indeed a problem worthy of deep thought.The "Shut Down Prompt" feature of AnQiCMS (AnQiCMS) is specifically designed to address this pain point, allowing us to communicate information to the front desk users in a friendly and clear manner

2025-11-09

How to configure the image processing method (Webp, compression, thumbnail) in AnqiCMS content settings to optimize front-end loading speed and display quality?

In the era where content is king, the loading speed and display quality of website images have a significant impact on user experience and search engine optimization (SEO).High-quality images, if they load slowly or are blurry, not only may deter visitors, but may also affect the website's ranking in search engines.Luckily, AnqiCMS provides a series of powerful and flexible image processing features to help us easily meet these challenges.Next, we will delve deeper into how to cleverly configure the image processing method in AnqiCMS content settings, including WebP

2025-11-09