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

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