How `include`, `extends`, and `macro` tags enhance the reusability and maintainability of template code?

Calendar 👁️ 66

Enhance the efficiency and maintainability of the AnQi CMS template:include/extendsandmacroingenious application

In the daily content operation of AnQi CMS, we often need to create and manage a large number of pages.How to ensure that these pages maintain consistency while also being developed and maintained efficiently is a challenge that every operator needs to face.include/extendsandmacroThese three core tags provide us with powerful tools to greatly enhance the reusability and maintainability of template code.

include: The art of code snippet splicing.

Imagine that each page of your website has the same header (Header), footer (Footer), or sidebar.If you were to repeat the same code segments in each page file, then changing a Logo, a section of copyright information, or a navigation link would mean having to modify dozens, if not hundreds, of files, which is undoubtedly catastrophic.

includeThe label is to solve this kind of repetitive labor.It allows us to save independent, reusable HTML code snippets in separate files and then insert them like a puzzle where needed.partial/header.htmlThe file is specifically used to store the website's header code. Then, simply use it in all places where the header needs to be displayed.{% include "partial/header.html" %}.

The advantage of this method is obvious:

  1. Highly modular:Divide the page into logically clear small modules, each responsible for its own content, improving the readability and management efficiency of the code.
  2. Easy maintenance:Page header or footer changes, just need to modifypartial/header.htmlThis file will be updated on all pages that reference it, greatly reducing maintenance costs and error rates
  3. Flexible parameter passing:includeThe tag also supports passing throughwithA keyword is used to pass variables to the template, allowing the imported fragment to display different content based on different contexts, thereby increasing reusability. For example, you can pass atitleVariable to give the page header, so that it displays the title of different pages.

ByincludeWe can abstract those static, almost unchanged public areas to make the template code more concise and organized.

extends: The way of page skeleton reuse.

If we sayincludeIs for the reuse of the "block" in the page, thenextendsThis is the reuse for the "page layout skeleton".In a website, many pages may have a similar overall layout, such as top navigation, sidebar, main content area, and footer copyright information.But the main content area may differ.

extendsTags allow us to define a "basic template" (usually namedbase.htmlorlayout.htmlThis basic template includes the overall structure and common elements of the website (such asincludethe header, footer). In the basic template, we can use{% block content %}Such tags define some areas that can be overwritten by child templates.

Then, other page templates (child templates) can{% extends 'base.html' %}Inherit this basic template and use the same named{% block content %}Fill in your own content.

extendsThe benefits brought are revolutionary:

  1. Unified website structure: Ensure that all pages follow a unified layout and style, enhancing user experience and brand image.
  2. Rapid iteration designWhen adjusting the overall layout of the website, only the basic template needs to be modified, and all pages inheriting it will be automatically updated, greatly accelerating the design iteration cycle.
  3. Focus on content development: Subtemplate developers do not need to concern about the overall structure of the page, just focus on filling inblockspecific content, which improves development efficiency and professionalism.

It should be noted that,{% extends %}The tag must be the first tag in the sub-template, which is like telling the template engine: 'I will build my page based on this skeleton.'

macro: A reusable component packaging tool

When there are some components with similar structures but dynamic content on the page, such as each product card in the product list, each comment in the comment list, or a unified style prompt with icons and text, simply usingincludeIt may not be very flexible, as it is mainly used to introduce static content or simple variables. At this time,macrothe tag comes into play.

macroIt can be regarded as a "function" or "component" in the template, which allows us to define a template code block with parameters. It's like writing a function in a programming language, where we can define amacroRender a product card and pass in parameters such as the product image, name, price, and so on.

For example, define a product card.macro:

{% macro product_card(product_image, product_name, product_price, product_link) %}
<div class="product-item">
    <a href="{{ product_link }}">
        <img src="{{ product_image }}" alt="{{ product_name }}">
        <h3>{{ product_name }}</h3>
        <p class="price">{{ product_price }}</p>
    </a>
</div>
{% endmacro %}

Then on the product list page, by looping through the data and calling thismacroto render each product:

{% import "macros/product_macros.html" as product_macro %} {# 假设宏定义在单独文件 #}
{% for product in products_list %}
    {{ product_macro.product_card(product.image, product.name, product.price, product.link) }}
{% endfor %}

macroThe value lies in:

  1. Ultimate reusabilityEncapsulate complex component logic, control its display through parameters, and avoid a lot of repeated HTML and logic code.
  2. Code is clearer: The template code becomes more concise and declarative, making it easy to see the structure of the page and the relationship between components at a glance.
  3. Easy to expand and modify:Adjust the style or structure of the component, just modifymacroDefine, all the places calling it will automatically take effect.
  4. Improve performance:Optimize throughmacroInternal logic, can improve rendering efficiency.

macrousually associates withimportThe labels are combined to organize macro definitions into separate files, keeping the main template clean.

Summary

Of Security CMSinclude/extendsandmacroLabels provide a layered, modular solution for template development.extendsResponsible for constructing the overall layout skeleton of the website, ensuring the uniformity of the page structure;includeUsed to embed static, reusable code snippets, enhancing the modularization degree; andmacroThe component encapsulates dynamic parameter components, achieving a higher level of code reuse and flexibility.

By reasonably using these three tags, not only can you significantly reduce the writing of repetitive code and improve development efficiency, but also make your website template structure clear and easy to manage, thus making it easy to maintain and iterate in the future, allowing AnQi CMS to truly become your powerful assistant for efficient operation.


Frequently Asked Questions (FAQ)

Q1:includeandmacroHow should I choose, as it seems that all of the code can be reused?

A1: They have their respective focuses. When you need to introduce a relatively static HTML fragment with little content change, or one that can be satisfied by a few global variables, useincludeSimpler and more direct, for example, the header, footer, and copyright information of a website. When you need to create highly configurable components whose content changes dynamically according to the input parameters,macroIs a better choice, for example, a product card, article list item, button group, etc., it can receive parameters like a function and render different content.

Q2: UseextendsCan a child template inherit variables defined in the parent template?

A2: Can be.The child template automatically inherits all available variables and context environments from the parent template when inheriting the parent template.setThe tag has redefined the same variable.

Q3: If I am{% extends %}What will happen after the label added other content (such as HTML code)?

A3: The template engine of Anqi CMS will report an error.{% extends %}The label must be the first label in the template file (excluding comments) because it defines the basic layout inherited by the current template.If you add other non-blank content after it, the template engine cannot correctly parse the inheritance relationship of the template, resulting in rendering failure.{% block %}Inside the tag.

Related articles

How to use the `stampToDate` tag to format a database timestamp into a readable date?

In website operation, we often encounter such situations: the time information stored in the database, such as the publication time of articles, the creation time of goods, etc., is often in the form of a series of numbers (timestamps).This string of numbers is clear to machines, but it has poor readability for us users.Imagine, if next to an article it displays '1678886400' instead of '2023/03/15', wouldn't that be a big discount in experience?AnQi CMS knows this and has provided a very practical template tag——`stampToDate`

2025-11-08

How to flexibly control the conditional display and loop iteration of logic tags such as `if` and `for` in the template?

In the world of AnQi CMS templates, we often need to display content based on different conditions or repeat a series of data, at this point, the `if` and `for` logical tags become particularly important.They are the foundation for building dynamic content and implementing flexible layouts in templates, allowing us to precisely control the presentation of every piece of information on the web page.

2025-11-08

How to use the `pagination` tag to generate a beautiful pagination navigation for articles or product lists?

In website operation, as the content volume continues to grow, whether it is articles, products, or other lists, how to efficiently organize and display these contents while ensuring a smooth user browsing experience and a friendly search engine is a problem that needs to be carefully considered.Page navigation is the key tool to solve this problem.AnQiCMS provides a powerful and flexible `pagination` tag that allows you to easily create beautiful and functional pagination navigation for various lists.

2025-11-08

How to use the `linkList` tag to display the list of friends' links on the website?

During the operation of our website, friendship links not only help to increase the amount of traffic, but are also an indispensable part of SEO optimization.A healthy link ecosystem that can effectively pass on weight and enhance the authority of the website.In AnqiCMS, managing and displaying friend links is very convenient, mainly due to its built-in `linkList` tag.This article will introduce in detail how to use the `linkList` tag to display the friend link list on your AnqiCMS website.

2025-11-08

How do `filters` (such as `truncatechars`, `safe`) format or sanitize the output content?

In the daily operation of AnQiCMS, the way content is presented and the security are the key factors that determine the professionalism and user experience of the website.AnQiCMS is a powerful template engine that draws many advantages from the Django template engine syntax, among which the 'filters' are the behind-the-scenes masters of content formatting and security processing.These filters can help us easily process output content, whether it is to simplify text, convert formats, or ensure the safety of the content, it becomes accessible.### Transformer: Content Output Transformer In simple terms

2025-11-08

How to render Markdown editor content correctly on the front-end page?

In AnQiCMS, Markdown is an efficient and widely popular content creation method.It uses a concise markup syntax, allowing creators to focus on the content itself without being troubled by complex layout tools.However, to present these concise Markdown texts to the user in the browser, it requires the collaborative processing of the AnQiCMS backend and the frontend template.Understanding this process can help you better utilize the content management capabilities of AnQiCMS, ensuring that your content is displayed in **status**.### Enable

2025-11-08

How to correctly display mathematical formulas and flowcharts in Markdown content?

With the popularity of the built-in Markdown editor of AnQiCMS, many users hope to be able to display information more flexibly in their website content, especially for technical documents, tutorials, or data analysis, the presentation of mathematical formulas and flowcharts has become particularly important.AnQiCMS integrates external libraries to bring powerful extension capabilities to Markdown content, making it easy and convenient to display professional content.

2025-11-08

How does the 'recommended attribute' of a document affect the call and display priority of content on the front end when it is published?

When using Anq CMS to manage website content, we often need to highlight certain important articles or products to make them easier for visitors to find.This is when the "recommended attribute" of content publishing comes into play.It is not a complex backend setting, but rather a very intuitive option that can be seen on the 'Add Document' interface every time we publish or edit a document. It is an important tool for effectively managing content display and call priority.

2025-11-08