How to reuse common HTML fragments in a template by using the `include` tag or define reusable code blocks by `macro`?

Calendar 👁️ 71

In the development and maintenance of website templates, we often encounter the need to reuse HTML code snippets or logical structures.If you copy and paste every time, it is not only inefficient, but also once you need to modify it, you have to repeat the operation in multiple places, which is easy to make mistakes.AnQi CMS knows this, it provides a template engine that follows the syntax of Django, throughincludeTags andmacroMacro function, allowing us to easily implement code reuse, greatly enhancing the maintainability and development efficiency of the template.

Reuse common HTML fragments: includeTag

Imagine that the top navigation bar and bottom copyright statement of our website appear on almost every page.If I had to write all this HTML code every time, it would be a nightmare.Secure CMS ofincludeThe tag is exactly the tool to solve this kind of problem. It allows us to embed an entire HTML file into another template file, like a puzzle.These common parts are usually referred to as "code snippets", such as headers, footers, sidebars, etc., which can be stored in the template directory.partial/In the directory, convenient for unified management and reference.

The simplest way to use it is to directly specify the file path to include. For example, we have one stored inpartialThe header file in the folderheader.htmlWe can introduce it like this in the main template:

{% include "partial/header.html" %}

Sometimes, the files we introduce may not be necessary for every page, or they may be optional components. In this case,includelabel'sif_existsThe parameter comes into play. With this parameter added, if the specified file does not exist, the system will not report an error but will silently skip the import operation, which is very useful for building flexible and variable page structures:

{% include "partial/header.html" if_exists %}

What's more powerful is,includeLabels can also allow us to pass specific data when introducing common segments. This is done bywithParameter implementation. For example, we hope that the common header can dynamically display the page title and keywords, but this information may differ on different pages. We can do it like this towardsheader.htmlPass data:

{% include "partial/header.html" with title="这是声明给header使用的title" keywords="这是声明给header使用的keywords" %}

Inheader.htmlInside, we can access these values as if we were using ordinary variables, through{{title}}and{{keywords}}Just separate multiple variables with spaces if we need to pass more than one.

Moreover, if we only want to letincludeThe template uses the explicitly specified variables, rather than inheriting all the context variables of the current template, and can be usedonlyParameters. This helps to keep the code clear, avoiding unnecessary variable pollution:

{% include "partial/header.html" with title="我的页面标题" keywords="SEO关键词" only %}

This meansheader.htmlCan only access intitleandkeywordsThese two variables, and cannot access any other variables in the main template.

In practical applications,includeThe tag is very suitable for reusing those areas with relatively fixed structures and slightly variable content, such as website navigation bars, footers, sidebars, and common advertising spaces.In this way, we can divide complex pages into multiple components, each responsible for its own content, thereby improving the readability and maintainability of the template.

Define reusable code blocks:macroMacro function

If we sayincludeTags are like bringing a ready-made block from somewhere, thenmacroMacro functions are like molds for making building blocks. They allow us to define reusable code blocks that can accept parameters and dynamically generate HTML content based on the parameters.macroThe function is more like a function in programming languages, with its own independent scope, handling only the passed parameters, which makes it very efficient in dealing with repeated, structurally similar but content-wise different elements.

Define a macro function is very intuitive, it ends with{% macro 宏名称(参数列表) %}and ends with{% endmacro %}. For example, if we often need to display the summary information of articles on the page, we can define a macro namedarchive_item:

{% macro archive_item(archive) %}
<li class="article-item">
    <a href="/archive/{{archive.Id}}" class="link">
        <h5 class="title">{{archive.Title}}</h5>
    </a>
</li>
{% endmacro %}

Where this macro needs to be used, we just need to pass the corresponding article data as we would call a function, for example, in an article list:

{% for item in archives %}
    {{ archive_item(item) }}
{% endfor %}

This way, each article list item will be sorted according toarchive_itemThe structure defined by macros is rendered.

To better organize template files, we can also store macro functions in separate template files (for examplearchive.helper), and then use them in other templates throughimportLabel import and use. This helps keep the main template concise and manage macro functions in categories:

{% import "archive.helper" as my_macros %}

After import, we can accessmy_macros.archive_item(item)in this form to call macros. Ifarchive.helperContaining multiple macros, we can also import them all at once, even set aliases for them, for convenience and differentiation.

macroMacro functions are particularly suitable for those that require high customization,

Related articles

How to retrieve and display user group details, such as group name, level, and purchase price, for a membership system?

Today in the operation of the website, building an efficient member system is crucial for content monetization, user stickiness cultivation, and community construction.AnQiCMS (AnQiCMS) provides a solid foundation for building such a system with its flexible design and rich features.Among them, the fine management of user groups is the core of the member system's operation, which allows us to provide differentiated service experiences based on the different identities and rights of users.### User Group Management in AnQi CMS: Basics and Value AnQi CMS built-in user group management function

2025-11-08

How to automatically parse URL strings to clickable `<a>` tags in the article body or description?

In daily website content creation and management, we often need to embed some links in the article body or description, such as referencing external resources, pointing to product pages, or other related articles.If these URLs are only displayed in plain text, users will have to manually copy and paste them into the browser, which undoubtedly will greatly reduce their user experience.幸运的是,AnQiCMS 内置了非常实用的功能,可以自动将这些 URL 字符串智能识别并转换为可点击的 `a` 标签,让网站内容更加友好和便捷。This function mainly through

2025-11-08

How can you clearly display the user's comment content, username, reply object, and posting time in the comment list?

In website content operation, the comment section is undoubtedly an important manifestation of user interaction and content depth.A well-designed, clear information presentation comment list that can significantly improve the user's browsing experience and effectively stimulate community activity.AnQiCMS's powerful template system provides us with flexible tools, allowing us to easily achieve the organization of comment content, commenters, reply objects, and posting time.### Understanding the Core Elements of Comment Lists To build a visually appealing and practical comment list, we need to ensure that several key pieces of information are presented intuitively

2025-11-08

How to use the `archiveFilters` tag to build a dynamic document filtering feature, such as filtering by product parameters?

Using AnQiCMS's `archiveFilters` tag to build an efficient and practical dynamic filtering function In the field of content management and e-commerce, users being able to quickly and accurately find the information they need is crucial for improving website experience and conversion rates.Imagine, when users browse products or documents on your website, if they can quickly filter out the content they want based on various conditions such as color, size, brand, and even more specific parameters like processor type, memory size, etc., this will greatly enhance their user experience.Provided by AnQiCMS

2025-11-08

How to set up image resource management in AnQi CMS and support batch regeneration of thumbnails in different sizes?

In website operation, images are not only an important part of the content, but also a key factor affecting page loading speed and user experience.Efficient image management can greatly enhance the performance and maintainability of a website.AnQiCMS (AnQiCMS) is well-versed in this field, providing users with comprehensive image resource management functions, especially excelling in thumbnail settings and batch processing, making image operations more convenient and flexible.### Core Feature Overview: AnqiCMS Image Management System AnqiCMS Image Resource Center is a collection of upload, classification, editing

2025-11-08

How to use `{filename}` or `{catname}` in pseudo-static rules to generate SEO-friendly custom URLs for articles, categories, and single pages?

In website operation, generating SEO-friendly URL addresses for content is a key link to improving website SEO performance.A clear, keyword-rich URL not only makes the page content easy for users to understand, but also helps search engines better understand and crawl web pages.AnQiCMS provides powerful custom static rule functionality, allowing us to flexibly use variables such as `{filename}` and `{catname}` to generate highly customized URLs for articles, categories, and even single pages.### Optimize URL

2025-11-08

How to display the current year or a custom formatted current date and time in the template?

## In Anqi CMS template, flexibly display the current date and custom time format In website operations, we often need to display date and time information dynamically on the page, whether it is the current year in the copyright statement, the publication time of articles, or the countdown of activities.The AnQi CMS provides a very flexible and easy-to-use method to display the current year or a custom date and time format in templates, keeping your website content up to date and enhancing user experience.The Anqi CMS template system adopts syntax similar to the Django template engine, making the display of dynamic content intuitive

2025-11-08

How to split a string into an array or concatenate array elements into a single string in a template?

During the development of Anqi CMS templates, we often encounter situations where we need to process strings, such as converting a text segment separated by a specific symbol into a list, or concatenating multiple items in a list into a continuous text.The Anqi CMS template engine provides powerful filters (Filters) to help us easily implement these operations, greatly enhancing the flexibility of the template. ### AnQi CMS Template Engine Basics The AnQi CMS template engine syntax is designed to be very user-friendly, similar to the Django template engine.It is mainly through double curly brackets

2025-11-08