How to use the `macro` macro function in AnQiCMS templates to define reusable content display segments to improve efficiency?

Calendar 👁️ 71

In AnQi CMS, efficiently managing website content and front-end display is the key to daily operations.When faced with some repeated page elements, such as article list items, product cards, or buttons with specific styles, if we rewrite the code each time, it not only takes time and effort, but is also prone to errors, and future modifications and maintenance will become particularly complex.macroThe macro function is the tool to solve this pain point, it can help us define reusable content display segments, thereby greatly improving development efficiency and the maintainability of templates.

macroA macro function, you can imagine it as a "mini-function" or "content component" in the template.It allows you to encapsulate a piece of HTML code with specific logic and style, and define some parameters for this code.When you need to use this code, just call the macro as a function and pass in the corresponding parameters, and you can quickly generate the desired content.This way, you avoid rewriting the same template code, making the template structure clearer and easier to manage.

Define a macro function

You will use a macro function to define in the Anqi CMS template{% macro %}and{% endmacro %}This is a label. A macro function needs a name, as well as a list of parameters that can be received, which are used like ordinary variables inside the macro.

We take a common scenario as an example: In various places on the website, you may need to display a structured article summary card, including the article title, link, introduction, and thumbnail. We can define a macro like this:

{# 定义在 /template/您的模板目录/partial/_article_card.html 文件中 #}
{% macro article_card(article) %}
<div class="article-card">
    <a href="{{ article.Link }}" class="article-link">
        {% if article.Thumb %}
            <img src="{{ article.Thumb }}" alt="{{ article.Title }}" class="article-thumb">
        {% endif %}
        <h3 class="article-title">{{ article.Title }}</h3>
        <p class="article-description">{{ article.Description|truncatechars:100 }}</p>
        <span class="article-date">{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
    </a>
</div>
{% endmacro %}

In this example, we define a macro namedarticle_cardthat takes a namedarticleparameter. Inside the macro, we usearticleproperties (such asLink/Title/Thumb/Description/CreatedTime)to construct the HTML structure. Please note that we usedtruncatecharsa filter to truncate the article summary, and usestampToDateThe function formatted the publish time, all of these are powerful features provided by the Anqie CMS template engine.

Introduce and use macros in the template.

Once you define a macro, you can call it in any template file where you need to use it. Anqi CMS encourages storing such reusable code snippets inpartial/In the directory, this structure is clearer.

Assuming you have defined the abovearticle_cardmacro saved/template/您的模板目录/partial/_article_card.htmlin the file. Now, in your home page template (such asindex/index.html) or other list page template, you can useimportLabel to introduce it:

{# 在 /template/您的模板目录/index/index.html 文件中 #}

{# 引入宏文件,并给引入的宏函数指定一个别名 card #}
{% import "partial/_article_card.html" as card %}

<section class="latest-articles">
    <h2>最新文章</h2>
    <div class="article-list-grid">
        {% archiveList articles with type="list" moduleId="1" limit="6" order="id desc" %}
            {% for item in articles %}
                {# 调用宏,并传入当前文章数据 #}
                {{ card.article_card(item) }}
            {% endfor %}
        {% empty %}
            <p>暂时没有文章发布。</p>
        {% endarchiveList %}
    </div>
</section>

<section class="recommended-articles">
    <h2>推荐文章</h2>
    <div class="article-list-flex">
        {% archiveList recommendedArticles with type="list" moduleId="1" limit="4" flag="c" order="views desc" %}
            {% for item in recommendedArticles %}
                {# 在另一个区域再次调用宏,显示推荐文章 #}
                {{ card.article_card(item) }}
            {% endfor %}
        {% empty %}
            <p>暂时没有推荐文章。</p>
        {% endarchiveList %}
    </div>
</section>

In this example:

  1. We use{% import "partial/_article_card.html" as card %}Introduced the macro file, and throughas cardGave the macro component a simpler namespace.
  2. Following, in the loop of different article lists (latest articles and recommended articles), we all called{{ card.article_card(item) }}. Here,itemthat isarchiveListthe data of each article looped out by the tag, which was passed as a parameter toarticle_cardmacro.

Imagine for a moment, if notmacro, you may need to change at eachforIn a loop, copy and paste the same HTML structure and data rendering logic.Once you need to modify the style or display content of an article card (such as adding a reading volume field), you will need to modify it one by one in all the places it is used, which is undoubtedly time-consuming and prone to errors.macro, you just need to modify_article_card.htmlThis file, all the places that refer to it will be synchronized for updates, greatly improving efficiency and consistency.

macroAdvantages and Application Scenarios

macroThe strength of macro functions is reflected in the following aspects:

  • Reduce code redundancy:Encapsulate repeated UI components to make your template code more concise.
  • Improve maintenance efficiency:Modify a macro definition, all places using it will be automatically updated, avoiding the cumbersome global search and replace.
  • Enhance code readability: The macro function abstracts complex HTML structures and logic into a simple call, making template code easier to understand.
  • Promote teamwork:Different developers can focus on developing different macros and then easily integrate them into the main template.

In addition to article cards,macroit can also be applied to many places, such as:

  • Product list items:On e-commerce websites, product cards are composed of product thumbnails, names, prices, buy buttons, and other elements.
  • Comments display:The display format of unified comment user avatar, username, comment content, and timestamp.
  • Breadcrumbs navigation item:If your breadcrumbs navigation has multiple styles or complex link logic.
  • Button Group:A combination of buttons with specific icons, text, and links.
  • Form Input Field:Standardized input box with labels, placeholders, and validation prompts.

By flexible applicationmacroMacro function, you will be able to build and maintain your safe CMS website template more elegantly and efficiently.


Frequently Asked Questions (FAQ)

1.macromacro functions andincludeWhat are the differences between tags? includeThe tag is used to directly insert the entire content of a template file into the current position, and it inherits all the context variables of the current template.macroThe macro function is more like an independent小程序, it only receives variables passed in as parameters, and has its own independent scope, and cannot directly access variables outside the macro definition. In simple terms,includeIs it to directly copy the code snippet?macroIs it to define a callable, parameterizable functional component?

2.macroCan macro functions access variables outside the macro?No.macroThe macro function has a limited scope and can only access variables passed through parameters.This means that if any data is needed within the macro, you must explicitly pass it as a parameter.This is to ensure the independence and reusability of the macro, to avoid its behavior being unexpectedly affected by the external environment.

3. Where should the macro file be placed in the template directory?It is strongly recommended to place the macro definition file in your template directory to maintain the clarity and standardization of the template structure.partial/In a subdirectory. For example, if your template directory isdefaultthen the macro files can be placed in/template/default/partial/_macros.htmlor further subdivided according to function, such as/template/default/partial/_article_snippets.htmlThis helps in managing and finding reusable code snippets.

Related articles

How to use the `include` tag in AnQiCMS templates, efficiently reuse and display common page header, footer and other modules?

When building a website, we often encounter such a scenario: the website header (Header), footer (Footer), sidebar (Sidebar), and navigation menu modules, almost appear on every page.These modules are not only similar in content, but also their structure and style need to be maintained consistently.If you write the same code for each page, it is not only inefficient, but also a maintenance nightmare if you need to make any changes, as you would have to adjust all pages one by one.Luckyly, AnQiCMS (AnQiCMS) understands the importance of template reuse

2025-11-08

How to set and accurately display the TDK (Title, Description, Keywords) on the homepage of AnQiCMS?

The homepage, just like the digital facade of your company or brand.It is not only the first impression of your visitors, but also the key to search engines evaluating the core value of your website.The TDK - Title, Description, and Keywords on the homepage play a crucial role in Search Engine Optimization (SEO).A well-set homepage TDK can effectively improve the ranking of the website in search results, attract more target users to click, and bring considerable traffic and conversion.

2025-11-08

How does AnQiCMS handle the conversion of uploaded image webp format, large image compression, and thumbnail generation to optimize display performance?

In this era of pursuing speed and visual experience, the loading efficiency of website images is directly related to user retention and search engine rankings.We all hope that the images on the website can be presented in high definition and quickly displayed to the user.AnQiCMS provides us with a very practical solution in image processing, through functions such as WebP format conversion, intelligent large image compression, and diverse thumbnail generation, which help us easily optimize website images and make the website run more smoothly.### WebP Format Conversion: The Balance of Lightweight and High Definition WebP

2025-11-08

How to overview the key operational data display of the AnQiCMS backend homepage (such as document quantity, visit trend, inclusion situation)?

The AnQi CMS backend homepage: A smart overview of website operations In the ever-changing internet environment, an efficient and intuitive website operation backend is undoubtedly the key to controlling the overall situation for operators.AnQiCMS (AnQiCMS) fully understands this, and the design philosophy of its backend homepage is to present the core operational data of the website in a clear and easy-to-understand way in front of you, so that you can have a clear understanding of the health status and operational performance of the website at the first time.

2025-11-08

How to implement the template inheritance function of AnQiCMS, so that the content block display of master page and sub page can be overlaid and customized?

How template inheritance in AnQiCMS allows the parent page and child page to perform their respective functions?In website content management, maintaining consistent page style while being able to flexibly modify local content is a goal pursued by many operators.AnQiCMS uses a syntax similar to the Django template engine, providing us with an elegant solution, that is, the powerful template inheritance feature.With this feature, we can cleverly design master pages and subpages, making the website structure both unified and highly customizable.

2025-11-08

How to safely output user-generated content in AnQiCMS templates to prevent XSS attacks from affecting the display of the page?

The website content operation is in progress, user-generated content (UGC) is undoubtedly a valuable resource for enhancing the vitality and interactivity of the website.Whether it is comments, messages, forum posts, or articles edited with a rich text editor, all of these greatly enrich the information ecology of the website.However, potential security risks come with UGC, the most common and severe of which is cross-site scripting (XSS) attacks.If not prevented, malicious script code may be executed in the user's browser, stealing user data, and tampering with the page

2025-11-08

How to format a timestamp into a readable format

## Let Time Speak: How to Format Timestamps into Readable Dates in Anqi CMS When operating a website, the timeliness of content is often a point of great concern for users.Whether it is the publication time of the article, the update time of product information, or the specific moment of user comments, clear and intuitive dates and times can greatly improve the user experience, and even have a positive impact on search engine optimization (SEO).However, in the backend of the content management system, we sometimes see time presented as a long string of numbers, like `1609470335`.

2025-11-08

How to filter and display content on the article list page based on specific conditions (such as recommended attributes)?

In our website content operation, the article list page often plays an important display role.We do not want to simply arrange the content mechanically according to the time of publication, but we hope to be able to flexibly filter and display articles based on certain conditions, such as the importance of the content, popularity, or whether it is recommended.AnQiCMS (AnQiCMS) was designed with these needs in mind from the outset, providing us with a simple yet powerful content filtering mechanism.

2025-11-08