How `include`, `extends`, and `macro` auxiliary tags optimize the template structure and affect the final display of content?

Calendar 👁️ 66

In website operations, template design is the key to building user experience and the efficiency of content presentation.AnQiCMS (AnQiCMS) with its flexible template engine, provides strong support for content management.include/extendsandmacroAuxiliary tags, which do not directly modify the content themselves, but deeply affect the final display effect and maintenance efficiency of the website through optimizing the template structure.

Understand and make good use of these tags, which can help us manage the website more efficiently, ensuring that the content is presented in a unified, beautiful, and easy-to-update manner to users.


includeLabel: Modularize your page, reuse common elements

Imagine that your website has a header navigation, footer information, sidebar, and many other elements that appear on almost every page.If each new page were to rewrite this code repeatedly, it would undoubtedly consume a lot of time and effort.It is even more麻烦 is that once these public areas need to be modified (such as replacing the Logo or updating the copyright information), you have to search and modify each page individually, which is not only inefficient but also prone to errors.

includeLabels are born to solve this pain point.Its function is very direct: it allows you to insert the content of one file from a template directly into another file.header.html/footer.htmlandsidebar.htmlAs independent template files. Then, simply use them in the page templates where they are needed.{% include "partial/header.html" %}This method can be introduced in this way.

This modular approach brings obvious advantages:

  • improve development efficiency: The code only needs to be written once and can be reused throughout the entire site.
  • Simplify maintenance work: Changes to common elements need to be made in a single file, and all pages referencing that file will update automatically.
  • Ensure consistency of the page.: The common parts of all pages come from the same source file, ensuring visual and functional consistency.

Furthermore,includeTags also support passing variables, such as{% include "partial/header.html" with title="我的网站" %}This allows the imported segment to display different dynamic content according to the context. If the referenced template file may not exist, you can also addif_existsParameters, avoid errors due to missing files.

extendsLabel: Build the page skeleton and implement a unified layout

If we sayincludeThe label solves the problem of page 'components' reuse, thenextendsThe label is more macro, it focuses on the overall 'skeleton' structure of the page.The web pages often have a similar overall layout: the top is Header, the bottom is Footer, the middle is the content area, and there may be a left or right sidebar.Although the content area varies greatly, the overall framework is relatively fixed.

extendsTags are the core of implementing template inheritance. They allow you to define a "base template" (usually base.htmlThis base template includes the common HTML structure, CSS inclusion, JavaScript scripts, and uses{% block 块名称 %}{% endblock %}Tags define the areas available for sub-templates to override.

For example,base.htmlMay have defined.block title(Page title) and.block content(Main content). Then, your specific page template (such as).index.html/article_detail.html) can be accessed through.{% extends 'base.html' %}Inherit this base template. The child template only needs to focus on filling or overriding the base template defined.blockarea, without concerning the overall structure of the base template.

The benefits of this template inheritance mechanism are:

  • Unified website layoutEnsure that all pages follow the same overall structure to enhance brand consistency.
  • Accelerate the creation of new pages: The new page only needs to inherit the base template and overwrite a few content blocks, which greatly reduces duplicate code.
  • Convenient for global adjustmentIf the overall layout of the website needs to be adjusted (such as changing the height of the Header or the style of the Footer), just modify the base template, and all pages inheriting it will automatically take effect.
  • Enhance content focus: Developers and content editors can focus more on content logic and the implementation of specific blocks, rather than repeatedly building page structures.

It should be noted that,extendsThe tag must be the first tag in the sub-template.

macroTag: Reusability of dynamic components, enhancing content flexibility.

When we need to reuse not only static HTML fragments, but also components that dynamically generate content based on different data,macrothe tag comes into play.macroSimilar to a function in a programming language, it allows you to define a code block with parameters, which can then be called multiple times in a template and passed different data.

For example, you might have a blog list, where each list item (article summary) has a very similar HTML structure, but the displayed article title, description, link, image, and so on are dynamic. At this point, you can define amacro:

{% macro article_card(article) %}
<div class="article-card">
    <a href="{{ article.Link }}">
        <img src="{{ article.Thumb }}" alt="{{ article.Title }}">
        <h3>{{ article.Title }}</h3>
        <p>{{ article.Description }}</p>
    </a>
</div>
{% endmacro %}

Then in the article list template, you can call it like this:

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

macroThe advantage of tags lies in:

  • High reusabilityFor dynamically generating HTML fragments, avoid rewriting large amounts of similar structures.
  • Highly flexible: Passed through parameters, onemacroCan adapt to various data sources and display requirements.
  • Code neat: Encapsulate complex component logic inmacro, making the main template code simpler and easier to read.
  • Conducive to collaboration: Team members can independently develop and maintain differentmacroComponent.

macroCan be defined within the current template file, or asincludeSimilarly, save to an independent auxiliary file (such ashelper.html), and then through{% import "helper.html" as my_macros %}Introduce, and then through{{ my_macros.article_card(item) }}Call it. This further enhances the organization and maintainability of the template.

How do they work together to optimize the final display of the content?

These auxiliary tags do not exist in isolation, they usually work together to build an efficient and easy-to-manage content display system.

A typical secure CMS template structure may look like this:

  1. Basic template (base.html): Use.extendsDefining the outermost page skeleton, including<html>/<head>/<body>tags, as well as the mainblockregions such asblock head_meta/block header/block content/block footeretc.
  2. Public segment (partial/Contents): Divide the common and relatively static elements such as the website header, footer, sidebar, and navigation menu into independent files, usingincludetags in the corresponding base template or subtemplateblockintroduced.
  3. Dynamic components(macro/Directory or local definition): for articles, product list items, comment blocks, and other repetitive components that need to be dynamically generated based on data, definitionmacro. ThesemacroIt can be called in any areablockwhere it is needed.
  4. Subpage template (such asarticle_detail.html/product_list.html): PassextendsInherits tagsbase.htmlThen rewriteblock contentor specificblockwhere they are combined useincludeIntroduce the common segment and callmacroto display specific content.

Through this hierarchical and modular design, the final display effect of the website content has been greatly optimized:

  • consistent user experience: Regardless of the type of page, users can feel the unified visual style and interaction logic.
  • Flexible content layout: Even under the unified framework, throughmacroWith different content query tags, it can also easily realize diversified content layout and display.
  • Responsive to changes quicklyNo matter whether it is SEO strategy adjustment, design style update, or new feature launch, it can take effect quickly by modifying the template file without affecting the existing content data.
  • Better SEO performance: A clear template structure helps search engines crawl and understand website content, avoid duplicate content, and improve inclusion efficiency.

Frequently Asked Questions (FAQ)

Q1:includeandmacroTags are used for code reuse, how should I choose?

A1:Although they all aim to reduce code duplication, their focus is different.include主要用于插入相对静态、不依赖动态数据变化的固定HTML片段,例如网站的头部、页脚等。你可以通过withPassing a few variables, but it is not as flexible as a function. AndmacroIt is more like a function with parameters, specifically used to generate dynamic HTML structures based on the input data. When you need to render the same structure but with different data multiple times (such as article list items, product display cards),macroIt is a better choice because it can better encapsulate logic and data.

Q2: If my base template (parent template) definedblockbut the child template did not override the correspondingblockWhat will happen?

A2:If the child template does not override the defined in the base templateblock, then the default content contained in theblockarea of the base template will be displayed. This means you can provideblockSet default content as a fallback mechanism, so that the integrity of the page and a certain display effect can be maintained when the child template does not provide specific content. If the base template'sblockIs empty, then the area will also be blank if the sub-template is not covered.

Q3: Can I use it in aincludefile againextendsorextendsin the sub-template.importWhat is a macro definition?

A3:Yes. AnQiCMS template engine supports the nested use of these tags. For example, yourbase.htmlYesincludeOneheader.html, and thisheader.htmlcan itself containmacrodefinition or invocation. Similarly, inextendsthe child template, you can fullyimportexternally definedmacroFiles are used to organize and render specific content areas on a page. This ability to nest and combine is the key to its high flexibility.

Related articles

How to format the timestamp label `stampToDate` to display time data in a readable format?

In a content management system, time data often exists in the form of a series of numbers, which we call a Unix timestamp.This form is very efficient for machine processing, but for us users, a string like `1678886400` is obviously not intuitive to understand the date and time it represents.AnQi CMS knows this point well, therefore it provides a very practical template tag `stampToDate`, which helps us convert these cryptic timestamps into the date and time format we are accustomed to reading.###

2025-11-07

How `if` logical judgment tags and `for` loop iteration tags control the conditional display and repeated display of content?

In the daily operation of Anqi CMS, we often need to decide which content should be displayed according to different business logic, as well as how to efficiently repeat the display of a large amount of similar content.At this time, the `if` logical judgment tag and the `for` loop traversal tag have become indispensable tools in template design.They allow us to flexibly control the conditional display and repetition of content, greatly enhancing the dynamicity and maintainability of the website.### The conditional display tool - `if` logical judgment tag The `if` tag is the basis for conditional content display in Anqi CMS templates

2025-11-07

How does the pagination tag `pagination` provide navigation and display control for long content lists?

In website operation, when our content list (whether it is articles, products, or other information) accumulates to a certain amount, displaying all content on a single page not only significantly affects the page loading speed but may also make visitors feel overloaded with information, making it difficult for them to find the content they are really interested in.At this point, a reasonable pagination mechanism is particularly important. AnQiCMS provides a powerful and flexible `pagination` tag, which helps us provide clear navigation and display control for long content lists, thereby greatly optimizing user experience and website performance.Core Function

2025-11-07

How to display the link list of cooperative website links with the tag `linkList`?

In website operation, friendship links (also known as cooperative website links) play an important role.They not only bring additional traffic to the website, but also help to improve search engine optimization (SEO) performance, enhance the authority and user trust of the website.In Anqi CMS, managing and displaying these links becomes very convenient, mainly due to its powerful template tag system, especially the `linkList` tag.### Flexibly display cooperative websites: `linkList` tag usage and basic principles `linkList`

2025-11-07

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

For many content creators, especially when it comes to technical articles, tutorials, or data reports, it has always been a challenge to clearly and accurately display mathematical formulas and complex flowcharts on web pages.The traditional HTML editing method is not only繁琐but also prone to errors.It is fortunate that the new version of AnQiCMS has introduced support for Markdown editors, which brings great convenience to handling such complex content.It makes the creation of technical content more efficient and elegant.

2025-11-07

How do variables such as `{id}`, `{filename}`, `{catname}`, `{module}` and others affect the display structure of the URL in static rules?

When operating a website, we often pay attention to the quality of the content and the performance of the website, but there is a detail that is often overlooked but is crucial, that is, the structure of the URL (Uniform Resource Locator).A clear and meaningful URL can not only enhance the user experience, but is also an indispensable part of search engine optimization (SEO).Our company, Anqi CMS, understands this well and provides flexible and powerful pseudo-static functions, allowing us to customize URLs that are both aesthetically pleasing and SEO-friendly according to our needs.

2025-11-07

How do the settings for image download, Webp format, large image compression, and thumbnail processing methods affect the display effect of the image in the content?

During the operation of a website, the presentation effect of images often directly affects user experience and the professionalism of content.Slow loading speed, inconsistent dimensions, format incompatibility, and other issues may cause visitors to leave.Fortunately, AnQiCMS provides us with a variety of powerful image processing features in the content settings, allowing us to manage images finely and create an excellent visual experience for website content.Next, let's delve deeper into how these features affect the display of website images. ### 1.

2025-11-07

How to efficiently convert the first letter of an English string to uppercase in AnQi CMS template?

In AnQi CMS template development, string formatting is a common requirement.Whether it is to display the title of an article, the nickname of a user, or the category name, sometimes we need to ensure that they are presented in a specific letter case, such as capitalizing the first letter of the English string.The powerful template engine of Anqi CMS provides a variety of flexible filters (Filter) to help us complete these tasks efficiently.### Meticulously using the `capfirst` filter: Capitalize the first letter Used to capitalize the first letter of an English string

2025-11-07