How to reference the common template code snippets (such as header and footer) in AnQiCMS to unify the display of the page?

Calendar 👁️ 64

It is crucial to maintain a unified page style in website content operation, to enhance user experience and maintenance efficiency.Imagine if your website had hundreds or even thousands of pages, and each page's header, footer, or sidebar needed to be manually modified, that would be a massive project. 幸运的是,AnQiCMS provides a powerful and flexible template system that can help you easily refer to and manage common code snippets, ensuring the consistency of website display.

AnQiCMS's template system draws on the syntax of the Django template engine, making it easy to learn and powerful. It allows.htmlThe template file organizes the page structure and places style, script, images, and other static resources in the suffix/public/static/Under the directory, it makes management neat and tidy. In practice, you will find that AnQiCMS mainly achieves the reference and unified display of common code snippets through two core methods: includeTags andextendsLabel (template inheritance).

ByincludeLabel embeddable reusable code snippet

includeThe tag is a very practical feature of the AnQiCMS template system, allowing you to isolate independent, small code snippets (such as page headers, footers, navigation menus, sidebars, advertisement spaces, or copyright information) into separate files, and then easily introduce them into any page that requires them.The benefits of doing this are obvious: when you need to modify these common elements, you only need to edit the corresponding fragment file once, and all pages that reference it will be updated synchronously, greatly improving maintenance efficiency.

For example, you can create a file namedpartial/header.htmlto store the unified header for all pages, and then create anotherpartial/footer.htmlPlace the footer. In the various page templates of your website (such asindex.html/{模型table}/detail.htmletc.), you can simply use{% include "partial/header.html" %}and{% include "partial/footer.html" %}to include it.

To enhance flexibility and robustness,includeThe tag also provides several useful parameters:

  • if_exists:This is a very considerate feature. If you are not sure whether a referenced template file is definitely present, you canincludeAdd after tagif_existsThis way, even if the file does not exist, the system will not report an error but will silently ignore it.This is particularly useful during development, or when you refer to some optional, non-core fragments.
  • withandonly:Sometimes, you may want to pass some specific variables to the imported fragment.withParameters allow you to define new variables when importing and pass them to the fragment. For example,{% include "partial/header.html" with title="我的网站标题" %}Willtitlepass the variable toheader.html. If you only want to use the imported fragmentwithPass the variables without inheriting all the variables of the current template, you canwiththen addonlyparameters such as{% include "partial/header.html" with title="我的网站标题" only %}.

It is clearly mentioned in the template conventions of AnQiCMS,partial/The catalog is used to store such code snippets, and likebash.htmlsuch files are recommended to store headers, footers, and other parts that are inherited by each page.

ByextendsBuild a unified page skeleton (template inheritance)

In addition to embedding independent code snippets, AnQiCMS also supports a more macro-level template reuse mechanism - template inheritance, which is mainly achieved throughextendsandblockTags work together to implement. Template inheritance is like designing a "master page" or "skeleton" for your website, where you can define a basic template (for examplebase.html), which includes the overall layout structure of the website (such as<head>parts, header, footer, sidebar, etc.), and useblocktag to define the area that can be overridden by the sub-template.

For example, you can inbase.htmlto define a namedcontentofblockArea:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}默认标题{% endblock %}</title>
    <!-- 这里引入公共CSS和JS -->
    {% include "partial/head_css.html" %}
</head>
<body>
    {% include "partial/header.html" %} {# 引入公共页头 #}
    <main>
        <aside>{% include "partial/sidebar.html" %}</aside> {# 引入公共侧边栏 #}
        <section>{% block content %}{% endblock %}</section> {# 定义内容区域 #}
    </main>
    {% include "partial/footer.html" %} {# 引入公共页脚 #}
    {% include "partial/foot_js.html" %}
</body>
</html>

Then, in your specific page template (such asarticle/detail.html), just use{% extends 'base.html' %}inheriting this skeleton, and useblocktags to overlay the same-named areas defined in the parent template.

{% extends 'base.html' %}

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

{% block content %}
    <h1>{{archive.Title}}</h1>
    <p>{{archive.Content|safe}}</p>
    <!-- 更多文章内容 -->
{% endblock %}

This way, all inheritedbase.htmlThe pages will all have the same header, footer, and sidebar, and the core content of the pages is filled independently by their respective templates. It should be noted that,{% extends %}The tag must be the first tag in your template file, and eachblocktag must appear in pairs.

Flexible auxiliary tags

exceptincludeandextends, AnQiCMS also providesmacroThe tag allows you to create small, parameterizable code logic snippets, similar to functions in programming languages.This is very useful for reusing complex HTML structures with specific input parameters, further improving the maintainability and reusability of templates.

In summary, AnQiCMS passes throughincludeTags andextendsThe tag provides a complete template reuse mechanism. Whether it is embedded in small public segments or building the overall layout of the website, these features can help you achieve a high degree of uniform display on the page, enhancing the overall professionalism and operational efficiency of the website.Utilize these tools flexibly, and your website content will be more consistent, easy to manage, and easier to provide visitors with a smooth browsing experience.

Frequently Asked Questions (FAQ)

Q1: Can I make a specific page not use the unified header or footer of the website?

Of course you can. If you have usedextendsThe tag performs template inheritance, the child template can redefine the header or footer location in the parent template.blockCover an area to display different content, or even leave it blank. If the header or footer is throughincludeTags introduce, you can create a different template for this specific page, or modify the template of this page, byincludereplacing the tag with the required content.

Q2:includeandextendsWhat are the specific differences between these template reuse methods, and how should I choose?

In simple terms,includeSuitable for inserting or embedding relatively independent, functional code snippets, such as sidebars, ad slots, copyright information, etc., which are usually part of the page.extendsIt is used to 'inherit' the overall structure and layout of a page, it defines the large skeleton, and throughblockLeave the area for filling in content. When you want all pages to have a unified overall structure, selectextendsWhen you want to reuse small, independent UI components across different pages, selectinclude. Both are often used together, for example inextendsinheritedbase.html, throughincludeintroducing common headers and footers.

Q3: If the public code snippet file I reference is accidentally deleted, will the website report an error? How can I avoid this situation?

If you are usingincludewhen labeling, simply written as{% include "path/to/fragment.html" %}then whenfragment.htmlWhen the file does not exist, the system will throw an error, causing the page to fail to display normally. To avoid this situation, you can use{% include "path/to/fragment.html" if_exists %}.if_existsAfter the parameter, even if the file does not exist, the system will silently ignore this inclusion, and the page will continue to render without an error, which is very useful for some non-core, optional fragment inclusions.

Related articles

How to define temporary variables in templates to assist in content display logic?

When using AnQiCMS for website content management, the flexibility of the template is crucial for achieving diverse content display.At times, we need not only to output data directly, but also to perform some temporary processing, calculation, or judgment based on business logic, at which point defining temporary variables in the template becomes particularly useful.This not only makes the template code more tidy, but also avoids repeated retrieval or calculation of the same data, thereby improving rendering efficiency and maintainability.The template engine syntax of AnQi CMS is similar to Django template engine

2025-11-08

How to format a timestamp into a readable date and time format for display in AnQiCMS?

The website content is updated frequently, each article, product, or comment has its creation and update time point.However, these times are usually stored in the background in the form of a series of numbers, which is what we commonly call timestamps.It is not friendly to display these timestamps to visitors, we need to convert them into a clear date and time format.In AnQiCMS, formatting these timestamps into the date and time format we are accustomed to is actually very simple and intuitive.The system comes with a powerful template tag that can help us easily achieve this.###

2025-11-08

How to use if/for tags in a template to control the conditional display and looping display of content?

When building and operating a website, the dynamic display and flexible management of content are key to improving user experience and operational efficiency.AnQiCMS (AnQiCMS) understands this point, therefore its template engine provides powerful and intuitive conditional judgment (`if`) and loop traversal (`for`) tags, allowing you to easily control the display logic of content and achieve highly customized page layouts.The template syntax of AnQi CMS borrows the concise style of Django template engine, with a very low learning cost.By mastering these core tags

2025-11-08

How to apply AnQiCMS pagination feature to the pagination display of article lists or Tag document lists?

In website content management, whether it is to display a large number of articles, products, or documents under categories, an efficient and user-friendly pagination function is crucial.It not only allows users to easily browse a large amount of content, avoid the slow loading caused by long pages, but also helps search engines better crawl and index website information.AnQiCMS is well-versed in this, providing intuitive and powerful pagination functions in template tag design, making it effortless to implement pagination display in article lists or Tag document lists.Understanding how AnQiCMS implements pagination

2025-11-08

How to use the template inheritance feature of AnQiCMS to build a consistent page skeleton and display local content?

During the process of website construction and operation, how to efficiently manage page layout, ensure consistency in visual style, and be able to flexibly adjust local content is a challenge faced by many operators.AnQiCMS provides a powerful template inheritance function, which can help us cleverly solve these problems, realize the structural management of website pages and the flexible display of content.Understand the core concept of template inheritance Imagine that template inheritance is like a blueprint or master template in architectural design.We first design a universal page skeleton, which includes the shared elements of all web pages

2025-11-08

How does AnQiCMS use static caching technology to improve page loading speed and content display efficiency?

In today's fast-paced online world, the loading speed and display efficiency of websites have become key indicators of user experience and search engine rankings.A responsive website can not only effectively retain visitors but also stand out in fierce competition.AnQiCMS (AnQiCMS) understands this, providing strong support for users to achieve fast website access and efficient content presentation through its built-in static caching technology.Understand static caching: The core mechanism of website acceleration To understand how AnQi CMS works, you first need to understand what static caching is

2025-11-08

How to prevent AnQiCMS website content from being maliciously scraped and add watermarks to images?

In the digital age, the value of original content is self-evident; they are the core of attracting traffic, building brands, and improving SEO rankings for websites.However, the risk of malicious collection of content and theft of images is also increasing.This not only harms the original creators' labor成果, but may also cause the website's ranking in search engines to be damaged, affecting brand reputation.As a website operator, we naturally hope to effectively protect our digital assets.The Anqi CMS is an efficient and comprehensive content management system that has always given full consideration to the importance of content security from the beginning of its design

2025-11-08

How to control access and display permissions for different user groups on AnQiCMS to achieve content monetization?

In the practice of content operation, effectively managing different users' access rights to content is a key link in realizing the commercialization of content value.Many content creators and enterprises hope to provide differentiated content services for users at different levels, such as exclusive paid membership, VIP content preview, or unlocking more in-depth information based on user levels.AnQiCMS provides a set of effective and flexible functions that help us easily meet these needs.### Core Mechanism: User Grouping and Content Permission Hierarchy AnQiCMS

2025-11-08