AnQiCMS template development: skillfully integrate common code snippets, making your website maintenance more efficient

When running a website, we often find that many pages share the same basic structure, such as the website header, footer, sidebar navigation, or a common advertisement section.If you have to rewrite this code for each page every time, not only is it inefficient, but once you need to modify it, you have to adjust it one by one, which is undoubtedly a nightmare for website maintenance.As AnQiCMS, an enterprise-level content management system developed in Go language, has fully considered this need in template design, it provides a flexible and powerful mechanism that allows us to easily introduce and manage these common code snippets, thereby greatly enhancing the development and maintenance efficiency of the website.

AnQiCMS's template system has borrowed the syntax style of the Django template engine, which allows engineers accustomed to front-end development to get started quickly. It uses.htmlAs a template file suffix, and place all template files in/templateUnder the directory. The static resources required by the website, such as styles, JavaScript scripts, images, and so on, are unified in the location of/public/static/In the catalog. This clear structure lays a solid foundation for our effective management of public code.

Next, we will delve deeply into the two main strategies for introducing header, footer, and other common code segments in the AnQiCMS template: usingincludeTag for code snippet reuse, as well as adoptingextendsTag for building template inheritance system

Flexible code snippet reuse:includeThe clever use of tags

Imagine that your website has a delicate navigation menu or a sidebar featuring the latest articles.These small and independent modules often need to appear on multiple pages. At this time,includeThe label is your helpful assistant, it is more like a "plug and play" code snippet, allowing you to break these reusable small code blocks into independent files, and then reference them where needed.

usually, these reusable small code blocks we would put in the template directory underpartial/the folder, for examplepartial/header.html(Header),partial/footer.html(footer),partial/sidebar.html(Sidebar) and so on. When you need to introduce this code on a page, you can simply use{% include "partial/header.html" %}with this syntax.

includeThe power of tags is not just limited to this. If you need to pass specific data to these segments, you can usewithKeywords. For example, your page header may need to display a dynamic title, you can pass it like this when introducing:

{% include "partial/header.html" with pageTitle="当前页面标题" %}

Thenpartial/header.htmlin, you can use it like a normal variable.{{ pageTitle }}It is noteworthy that by default,includeThe template being entered inherits all variables from the parent template. But if you want the fragment to only use the variables you explicitly pass, and not inherit all variables from the parent template, you can useonlyKeywords such as{% include "partial/header.html" with pageTitle="当前页面标题" only %}This helps to avoid variable name conflicts and make code snippets more independent and controllable.

In addition, if you are unsure whether a code snippet file exists, you can useif_existsAvoid program errors,{% include "partial/optional_ad.html" if_exists %}This style of writing, when the file does not exist, will be automatically ignored without affecting the rendering of the page.

Build the website skeleton:extendsThe template inheritance system of tags

For the overall layout of the website, such as the shared HTML structure, CSS and JavaScript file references, the top navigation bar, and the bottom copyright information, we tend to use template inheritance.extendsTags allow you to define a website's 'skeleton' or 'template' (usually namedbase.htmlorbash.htmlThis skeleton contains the common structure of all pages. Then, other child page templates only need to "inherit" this skeleton and fill in or modify the specific areas defined within.

Inbase.html(orbash.htmlThis skeleton file, you need to use{% block name %}and{% endblock %}to define areas that can be overridden or filled by child pages. For example:

<!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 href="{% system with name="TemplateUrl" %}/css/style.css" rel="stylesheet">
    {% block head_extra %}{% endblock %}
</head>
<body>
    {% include "partial/header.html" %} {# 这里可以再引入一个页头片段 #}

    <main class="container">
        {% block content %}
            {# 这是主要内容区域,子页面会覆盖它 #}
        {% endblock %}
    </main>

    {% include "partial/footer.html" %} {# 这里可以再引入一个页脚片段 #}
    {% block body_extra %}{% endblock %}
</body>
</html>

On the abovebase.htmlIn it, we definedtitle/head_extra/contentandbody_extraMultiple blocks. When the child page needs to use this skeleton, it only needs to be declared at the top of the file{% extends 'base.html' %}and then it can be overwritten accordinglyblockto customize the content:

{# article/detail.html #}
{% extends 'base.html' %}

{% block title %}
    <title>{% archiveDetail with name="Title" %} - {% system with name="SiteName" %}</title>
{% endblock %}

{% block head_extra %}
    <link rel="stylesheet" href="{% system with name="TemplateUrl" %}/css/article-detail.css">
{% endblock %}

{% block content %}
    <article>
        <h1>{% archiveDetail with name="Title" %}</h1>
        <div>
            {% archiveDetail with name="Content" render=true|safe %}
        </div>
    </article>
{% endblock %}

It should be noted that,{% extends %}The tag must be the first tag in the child page template file, otherwise the template inheritance will not work properly.

How to choose and combine usage?

UnderstoodincludeandextendsThe principle after, which way to choose becomes clear:

  • UseextendsBuild global layoutWhen you need a unified page framework, such as all pages having the same header, footer, and sidebar location, but the middle content area is different.extendsIs**Select. It provides a solid and consistent skeleton for your website.
  • UseincludeModular local componentFor those small, self-contained code blocks that can be used independently at different locations on a website (such as breadcrumb navigation, contact module, comment form, etc.),includeTags can help you encapsulate them into independent segments. Even, you canbase.htmldo so through such a parent template.includeUse tags to introduce your header and footer fragments for more refined modular management.

For example, yourbase.htmlskeleton can be used{% include "partial/header.html" %}and{% include "partial/footer.html" %}to introduce the common header and footer, whilepartial/header.htmlandpartial/footer.htmlIt is an independent fragment file that contains the specific HTML code for the header and footer.This combination of use can ensure the consistency of the website structure and make each functional module highly flexible and maintainable.

In short, AnQiCMS provides template functions that encourage developers to organize code using modular and inheritance thinking. By reasonably utilizingincludeandextendsYou can greatly improve the development efficiency of website templates, simplify the subsequent modifications and maintenance work, and make website operation more efficient and composed.


Frequently Asked Questions (FAQ)

  1. How to beincludeDo you use the variables from the parent template in the file?Answer: By default, when a template file isincludeWhen you go to another template, it will automatically inherit all variables defined in the parent template. This means you can use anyincludein the file directly using any{{ 变量名 }}. If you only want toincludeThe file uses specific variables, which can beincludeadd awithused as keywords to pass variables, and you can choose toonlyuse keywords to limit the use to only these explicitly passed variables, such as{% include "partial/nav.html" with activePage="about" only %}.

  2. **includeandextendsWhat is the essential difference, how should I choose?