How to optimize page layout and content display by using the template inheritance (`extends`) tag?

Calendar 👁️ 58

In AnQiCMS, templates are the foundation for building the website's appearance and layout.A well-designed template not only makes the website look professional and beautiful, but also greatly improves the efficiency of content operation and the convenience of website maintenance.Among many powerful template tags,extendsThe tag is undoubtedly one of the key tools for optimizing page layout and content display.It can help us build a unified and flexible website structure, making content operation and front-end development more convenient.

Understandingextends: The core of template inheritance.

extendsThe core idea of the tag is 'code reuse' and 'layered management'.Imagine, each page of a website typically has a common header, footer, navigation bar, and some general styles and script references.If each page is written independently, not only is the workload huge, but any small change later on also needs to be modified one by one, which is inefficient and prone to errors.

extendsThe appearance of tags is to solve this problem. It allows us to define a "skeleton" template (usually namedbase.htmlOr a similar general name), this skeleton template includes the common HTML structure, header references, and footer information for all pages of the website. In the skeleton template, we useblockThe tag defines some areas that can be filled or modified by child templates, such as the page title, main content area, sidebar, or specific script inclusion positions.

When we need to create specific pages (such as the homepage, article detail page, category list page, etc.), we no longer need to write all the code from scratch, but only use this specific sub-template.{% extends 'base.html' %}Tag to inherit the skeleton template. Then, according to the characteristics of the page itself, rewrite the skeleton template defined in it.blockThe area should be filled with content unique to this page. In this way, the child template only needs to focus on its core content, while the common part is managed by the parent template.

It should be noted that,extendsThe tag must be the first tag in the sub-template file, otherwise the template inheritance mechanism will not work properly.

AnQiCMS inextendspractical application and advantages

toextendsTags applied to AnQiCMS template development can bring many significant advantages:

  1. Unified website structure and style:Through a publicbase.htmlWe can easily unify the overall layout, navigation, footer, and references to CSS and JavaScript of the website.This means that regardless of how many pages your website has, they will all have a consistent look and feel.For example, you canbase.htmlIntroduce the website's logo, main navigation menu, website filing number (through{% system with name="SiteLogo" %}/{% navList navs %}/{% system with name="SiteIcp" %}tags) and general style files, ensuring they are displayed correctly on all pages.

  2. Improve development efficiency:Developers do not need to rewrite the HTML document structure on each page,<head>Label content, common components, and so on. They only need to focus on the unique content and features of specific pages. For example, in the template of the article detail page, you just need to rewritemain_contentA block to display the article title, body (through{% archiveDetail with name="Title" %}/{% archiveDetail with name="Content" %}etc. tags), without concerning how the header and footer are presented.

  3. Simplify maintenance and updates:Any modification to the public part of the website (such as changing navigation links, updating the website logo, adjusting the overall layout), justbase.htmlPerform once in the skeleton template, all pages inheriting the template will automatically apply these changes.This significantly reduces the maintenance cost of the website, especially for websites with a large number of pages, its value is self-evident.

  4. Optimize content management and collaboration:Front-end developers can focus on designing and maintaining template structures, while content operations personnel can publish content through the backend system, which will automatically fill in the preset module sections.The structure and content are separated, making team collaboration more efficient.

  5. Keep the code neat and readable:Modular template code makes each file have a clear responsibility, easy to understand and debug.The code of child templates is usually smaller, only containing content directly related to the page, which improves the readability and maintainability of the code.

Practice exercise: Build an expandable page layout

Let's look at a simple example of how to use it in AnQiCMSextendsandblockBuild a flexible page layout.

1. Createbase.htmlSkeletal template:This file defines the overall structure of the website.

<!DOCTYPE html>
<html lang="{% system with name='Language' %}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {% 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/main.css">
    {% block head_extra %}
        {# 用于引入页面特有的CSS或Meta标签 #}
    {% endblock %}
</head>
<body>
    <header class="site-header">
        <div class="container">
            <a href="{% system with name="BaseUrl" %}" class="site-logo">
                <img src="{% system with name="SiteLogo" %}" alt="{% system with name="SiteName" %}">
            </a>
            <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>
        </div>
    </header>

    <main class="site-main">
        <div class="container">
            {% block main_content %}
                {# 这是所有页面共享的主内容区域,子模板可以重写它 #}
                <p>这里是默认的主内容。</p>
            {% endblock %}
        </div>
    </main>

    <footer class="site-footer">
        <div class="container">
            <p>{% system with name="SiteCopyright" %}</p>
            <p><a href="https://beian.miit.gov.cn/" rel="nofollow" target="_blank">{% system with name="SiteIcp" %}</a></p>
        </div>
    </footer>

    <script src="{% system with name="TemplateUrl" %}/js/jquery.min.js"></script>
    {% block footer_scripts %}
        {# 用于引入页面特有的JavaScript脚本 #}
    {% endblock %}
</body>
</html>

In the abovebase.htmlIn it, we definedtitle/head_extra/main_contentandfooter_scriptsFourblockarea.titleandmain_contentTypically, each page will have different parts, whilehead_extraandfooter_scriptsIt makes it easy to introduce unique resources for the page.

2. Createindex.htmlHome template:The home page needs to display some featured content.

{% extends 'base.html' %} {# 继承 base.html 骨架模板 #}

{% block title %}
    <title>AnQiCMS 官网 - 您的企业级内容管理专家</title> {# 重写页面标题 #}
{% endblock %}

{% block head_extra %}
    <link rel="stylesheet" href="{% system with name="TemplateUrl" %}/css/home.css"> {# 首页特有样式 #}
{% endblock %}

{% block main_content %}
    <section class="hero-section">
        <h1>欢迎使用 AnQiCMS</h1>
        <p>高效、可定制、易扩展的内容管理解决方案。</p>
        <a href="/about" class="btn btn-primary">了解更多</a>
    </section>

    <section class="latest-articles">
        <h2>最新文章</h2>
        <div class="article-list">
            {% archiveList archives with moduleId="1" type="list" limit="4" %}
                {% for item in archives %}
                    <article>
                        <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
                        <p>{{ item.Description|truncatechars:100 }}</p>
                        <time>{{ stampToDate(item.CreatedTime, "2006-01-02") }}</time>
                    </article>
                {% endfor %}
            {% endarchiveList %}
        </div>
    </section>
{% endblock %}

{% block footer_scripts %}
    <script src="{% system with name="TemplateUrl" %}/js/home-animations.js"></script> {# 首页特有脚本 #}
{% endblock %}

3. Createarticle_detail.htmlArticle detail page template:The article detail page needs to display the full content of the article and may include related recommendations in the sidebar.

{% extends 'base.html' %}

{% block title %}
    <title>{% archiveDetail with name="Title" %} - {% tdk with name="Title" siteName=true %}</title> {# 文章详情页标题 #}
{% endblock %}

{% block main_content %}
    <div class="row">
        <div class="col-md-9 article-content">
            <h1>{% archiveDetail with name="Title" %}</h1>
            <div class="article-meta">
                <span>分类: <a href="{% categoryDetail with name='Link' %}">{% categoryDetail with name='Title' %}</a></span>
                <span>发布日期: {{ stampToDate(archive.CreatedTime, "2006-01-02") }}</span>
                <span>浏览量: {% archiveDetail with name="Views" %}</span>
            </div>
            <div class="article-body">
                {% archiveDetail articleContent with name="Content" render=true %}{{ articleContent|safe }}
            </div>
            <div class="article-tags">
                {% tagList tags with itemId=archive.Id limit="10" %}
                    {% for item in tags %}
                        <a href="{{ item.Link }}" class="tag">{{ item.Title }}</a>
                    {% endfor %}
                {% endtagList %}
            </div>
        </div>
        <aside class="col-md-3 sidebar">
            <h3>相关推荐</h3>
            <ul>
                {% archiveList related_articles with type="related" limit="5" %}
                    {% for item in related_articles %}
                        <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
                    {% endfor %}
                {% endarchiveList %}
            </ul>
        </aside>
    </div>
{% endblock %}

In these sub-templates, we rewriteblockCustomize the specific part of the page. You can see that each sub-template has relatively few lines of code, focusing only on its unique content, while the common header, footer, and so on are provided bybase.html.

How toblockDo you want to retain the parent template content?Sometimes, you may want to rewrite a certainblockwhile retaining the parent template of thatblockdefault content. In this case, you can use{{ block.super }}. For example, if you want to put in the child template'sfooter_scriptsAdd a new script while not overwriting the existing scripts in the parent template, you can do it like this:

{% block footer_scripts %}
    {{ block.super }} {# 引入父模板中 footer_scripts 的内容 #}
    <script src="{% system with name="TemplateUrl" %}/js/page-specific.js"></script> {# 添加自己的脚本 #}
{% endblock %}

This, the default script of the parent template and the specific script of the child template will be loaded, achieving the叠加 of content.

Summary

extendsThe tag is an extremely powerful feature of the AnQiCMS template system, which helps us achieve a high degree of uniformity in website layout, a significant improvement in development efficiency, and an effective reduction in maintenance costs. Whether it is to build a corporate website, marketing site, or personal blog, it is essential to master its use.extendsTags will make your website more scalable and sustainable. Embrace template inheritance to make the operation and development of your AnQiCMS website easier and more efficient.


Frequently Asked Questions (FAQ)

Q1:extendsIs the tag must be the first tag in the sub-template?Yes,extendsThe tag must be a sub-template file

Related articles

How to define and call the `macro` tag in AnQiCMS template to display reusable code blocks?

AnQiCMS provides a flexible and powerful template system, making the display of website content efficient and beautiful.In template development, in order to enhance the reusability and maintainability of code, we often encounter the need to encapsulate a commonly used code snippet so that it can be called in different places.This is when the `macro` tag becomes the key tool to achieve this goal.It allows us to define reusable code blocks, like functions in programming languages.Why do we need the `macro` tag?

2025-11-08

How to avoid extra blank lines when template logical tags (such as if, for) are rendered on the page?

When developing templates in AnQiCMS, we often find that even though the template code itself looks neat, the final rendered HTML page may still contain some unexpected blank lines.These blank lines do not affect the page function, but may make the HTML source code look less tidy, and even in some extreme optimization scenarios, it may bring a slight increase in file size.For users who pursue code aesthetics and concise output, how to effectively avoid these redundant blank lines is a topic worth discussing.

2025-11-08

How to loop through a list of data in a template and display it (using for loop), supporting counting and reversing?

In Anqi CMS template, efficiently displaying list data is an indispensable part of website content operation.Whether it is to display the latest articles, product lists, category directories, or customized data sets, flexible looping through these data and fine-grained control can greatly enhance the performance and user experience of the website.The Anqi CMS provides a powerful and easy-to-use template engine, its `for` loop tag is rich in features, supporting not only basic iteration but also easily implementing counting, reversal, and more advanced operations.### Core Concept: `for`

2025-11-08

How to implement conditional (if/else) dynamic display of content and layout in a template?

In website operations and frontend development, we often need to flexibly display content or adjust the page layout according to different situations.This dynamic ability is the core value of the conditional judgment tag (`if/else`) in AnQiCMS templates.The Anqi CMS template engine is simple and powerful, allowing us to set logic on the page like writing program code, making the website content show endless possibilities.### The Dynamic Beauty of AnQi CMS Template

2025-11-08

How to declare a temporary variable in AnQiCMS template and use it to display content, improving template flexibility?

In the template creation of Anqi CMS, we often need to display various dynamic content.It is crucial to be proficient in using temporary variables to make templates more flexible and code more concise.The Anqi CMS template engine provides powerful functionality for declaring temporary variables, which helps us better organize and process data, thereby improving the efficiency and maintainability of content display.### Understanding the Value of Temporary Variables Imagine that you need to display processed data at multiple locations on the page, or that a piece of data is used repeatedly in conditional judgments, or that data obtained from a tag needs to be further processed before it can be presented

2025-11-08

How to obtain and display the title and detailed content on the article detail page?

Manage website content in Anqi CMS, the article detail page is an important window for displaying core information to visitors.Whether it is corporate news, product introduction, or technical articles, clearly presenting the title and detailed content is the key to improving user experience and information communication efficiency.The Anqi CMS provides intuitive and powerful template tags, making content presentation easy and flexible. ### Understanding Anqi CMS Template Structure Anqi CMS template files are usually stored in the `/template` directory and follow a set of simple naming conventions.for the detail page of an article or product document

2025-11-08

How to correctly display images in the article content of AnQiCMS templates and support lazy loading of images?

In content operation, exquisite images can significantly enhance the attractiveness and reading experience of articles.However, image files are often large, and if not handled properly, they may slow down page loading speed, affect user experience, and even search engine rankings.AnQiCMS fully understands this, providing a flexible way to correctly display images in article content within templates, and supports lazy loading of images to balance aesthetics and performance.### Core: Display images in article content In the AnQiCMS template, to obtain the main content of the article, we mainly rely on `{%

2025-11-08

How to display the name, link, and hierarchy of the article category on the article detail page?

AnQi CMS is a flexible and efficient content management system that provides great freedom in content display.For a website, the article detail page not only needs to display the content of the article itself, but also the name, link, and even the hierarchical relationship of the category it belongs to, which are all important components for improving user experience, optimizing website structure, and promoting SEO.Clear categorization information can help users quickly understand the positioning of the article, facilitate their further browsing of related content, and also enable search engines to better crawl and understand the structure of the website.Next, we will discuss how to use the Anqi CMS article detail page

2025-11-08