How to define and use macro functions to create reusable code blocks in AnQiCMS templates?

Calendar 👁️ 56

As an experienced CMS website operation person, I know that the template function of the content management system is crucial for improving the efficiency of website operation and the quality of content display.AnQiCMS's powerful Django template engine syntax provides us with flexible content presentation capabilities, and the Macro function feature is an essential tool for code reuse, simplifying template structure, and improving development and maintenance efficiency.

During the process of content creation and publication, we often encounter some repetitive code snippets, such as the display format of article lists, the layout of product cards, and the specific structure of navigation menus.If copying code blocks every time, it not only increases the size of the template file and reduces readability, but also brings huge workloads and error risks in later modifications.The appearance of macro functions is to solve this pain point, it allows us to encapsulate these reusable code logic, and use them flexibly in templates like calling a function.

AnQiCMS Template Engine and Macro Function

AnQiCMS uses a template engine syntax similar to Django, which makes it very flexible and easy to use in template creation.The macro function as one of its auxiliary tags is essentially a template code snippet with parameters, it has an independent scope, and only handles the parameters passed in. This is similar toincludeThe tags are different,includeThe tag inherits and uses all the context variables of the current template, while the macro function is more focused on its own received parameters, making the macro function more modular and independent.

Define reusable code blocks: macro function syntax

Macro functions are passed through{% macro macro_name(参数列表) %} ... {% endmacro %}to define its structure.macro_nameis the name you give to the macro function, and参数列表The variables required by the macro function at runtime, which will be visible and used within the macro function.The logic inside the macro function can be any valid template code, including HTML structure, other tags, variable output, etc.

For example, we often need to display a brief summary of articles at different locations on a website, which may include title, link, description, and publication date. We can define a macro function for this:

{% macro render_article_item(article) %}
<li class="article-item">
    <a href="{{ article.Link }}" class="article-link">
        <h5 class="article-title">{{ article.Title }}</h5>
    </a>
    <p class="article-description">{{ article.Description|truncatechars:100 }}</p> {# 截取前100字符 #}
    <span class="article-date">{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
</li>
{% endmacro %}

in thisrender_article_itemIn the macro function,articleIt is a parameter passed in, representing a specific article data object. Inside the macro function, it accessesarticlethe object'sLink/Title/DescriptionandCreatedTimeProperties such as, to build the HTML structure of the article list item. We also usedtruncatecharsThe filter extracted the description text and usedstampToDateThe function formatted the timestamp, all of these are powerful features provided by the AnQiCMS template engine.

Effectively use macro functions in the template.

After defining the macro function, we can call it through{{ macro_name(参数值) }}the syntax in the template.

Using the macro function in the same template file

If the macro function is defined in the current template file, it can be called anywhere in the file as needed. This applies to some local code blocks that are used multiple times within the current template.

{# 假设render_article_item宏函数已在当前文件顶部定义 #}

<h2>最新文章</h2>
{% archiveList latest_articles with type="list" limit="5" %}
    <ul class="latest-articles-list">
        {% for article in latest_articles %}
            {{ render_article_item(article) }} {# 直接调用宏函数并传入文章对象 #}
        {% endfor %}
    </ul>
{% empty %}
    <p>暂时没有最新文章。</p>
{% endarchiveList %}

Import and use macro functions across template files

It is recommended to define macro functions in independent template files for better management and organization, usually these files are stored in a subdirectory of the template directory, for examplepartial/macros/. This can achieve the global reuse of macro functions and avoid the main template file from becoming too large.

Suppose we created a file namedmacros/common_macros.htmlfile, where multiple general macro functions are defined, such as:

File:templates/your_template/macros/common_macros.html

{# templates/your_template/macros/common_macros.html #}

{% macro render_article_item(article) %}
<li class="article-item">
    <a href="{{ article.Link }}" class="article-link">
        <h5 class="article-title">{{ article.Title }}</h5>
    </a>
    <p class="article-description">{{ article.Description|truncatechars:100 }}</p>
    <span class="article-date">{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
</li>
{% endmacro %}

{% macro render_product_card(product) %}
<div class="product-card">
    <img src="{{ product.Thumb }}" alt="{{ product.Title }}">
    <h3><a href="{{ product.Link }}">{{ product.Title }}</a></h3>
    <p class="product-price">${{ product.Price | floatformat:2 }}</p> {# 格式化价格为两位小数 #}
    <button class="add-to-cart">加入购物车</button>
</div>
{% endmacro %}

Now, in any template file that needs to use these macro functions (such asindex.htmlordetail.html), we can useimporttags to import them.importThe syntax of the tag is{% import "文件路径" macro_name1, macro_name2 as alias_name, ... %}. Among them,asKeywords allow us to set an alias for imported macro functions to avoid naming conflicts or to use a more concise name.

File:templates/your_template/index.html

`twig {# templates/your_template/index.html #}

{% import “macros/common_macros.html” render_article_item, render_product_card as product_card_renderer %}

{% extends "base.html" %} {# Assume the page inherits from base.html #}

{% block content %}

<section class="latest-news">
    <h2>最新资讯</h2>
    {% archiveList latest_articles with type="list" moduleId="1" limit="3" %} {# 假设文章模型ID为1 #}
        <ul class="latest-articles-list">
            {% for article in latest_articles %}
                {{ render_article_item(article) }} {# 调用导入的文章宏函数 #}
            {% endfor %}
        </ul>
    {% empty %}
        <p>暂无最新资讯。</p>
    {% endarchiveList %}
</section>

<section class="featured-products">
    <h2>热门产品</h2>
    <div class="featured-products-grid">
        {% archiveList featured_products with type="list" moduleId="2" limit="4" %} {# 假设产品模型ID为2 #}
            {% for product in featured_products %}

Related articles

How to use the `extends` tag in AnQiCMS templates to achieve template inheritance and content rewriting?

In the daily operation of AnQi CMS, we know that high-quality, well-structured website content is the key to attracting and retaining users.This is not only reflected in the words of the article, but also in the overall user experience and maintenance efficiency of the page.AnQi CMS, with its powerful functionality based on the Django template engine syntax, provides us with an efficient template inheritance mechanism, which is exactly what we are going to delve into today - how to use the `extends` tag to achieve template inheritance and content rewriting.

2025-11-06

How to include other template files in AnQiCMS templates (such as public header/footer)?

In the daily operation of AnQiCMS, efficient content management is not only reflected in the background data processing, but also cannot do without flexible front-end template design.For website operators, extracting common parts (such as navigation bars, footers, sidebars, etc.) and managing them independently, and introducing them to each page in a unified way, is the key to improving work efficiency, maintaining website consistency, and simplifying maintenance.AnQiCMS provides a powerful and intuitive template introduction mechanism, making this process effortless.AnQiCMS's template system is based on Go language and has borrowed from

2025-11-06

How to declare and assign variables in AnQiCMS templates for subsequent use?

As an experienced security CMS website operator, I am well aware of the importance of template design for website content display and user experience.Using variables in templates is the key to customizing pages and improving development efficiency.Today, I will elaborate on how to declare and assign variables in the AnQiCMS template, so that you can build and manage your website content more effectively.

2025-11-06

How to format a timestamp into a readable date and time in the AnQiCMS template?

As an experienced CMS website operation personnel of an enterprise, I know that every detail of user experience is crucial in content management.Clarity in presenting dates and times often directly affects readers' perception of the timeliness and professionalism of the content.Today, I will give a detailed explanation of how to convert those mysterious timestamps into the readable date and time format that we are accustomed to in the AnQiCMS template.

2025-11-06

How to cut, replace, or format strings in AnQiCMS templates?

As an experienced CMS website operation personnel in a safety company, I fully understand the importance of content in attracting and retaining users.A powerful and flexible template system that allows us to accurately present content according to different scenarios and user needs.AnQiCMS with its Django template engine syntax, provides us with rich string processing capabilities, whether it is for slicing, replacing, or formatting, it can be easily realized, thus transforming the original data into captivating web content.### AnQiCMS in template string variable acquisition and basic processing in

2025-11-06

How to ensure safe output of HTML content without escaping in AnQiCMS templates?

As an experienced website operator proficient in AnQiCMS, I am well aware of the importance of secure content output, while also ensuring the complete presentation of high-quality content.In AnQiCMS template development, dealing with HTML content often encounters a core issue: how to ensure that these HTML contents are rendered as expected and not escaped to plain text by the template engine?This not only involves the display effect of the content, but also concerns the security of the website.AnQiCMS uses a syntax similar to the Django template engine, one of its core design philosophies is security.This means

2025-11-06

How to judge if a variable is empty in AnQiCMS template and set a default value?

As a senior AnQi CMS website operation personnel, I know that handling variables with flexibility and robustness is crucial in template development and content display.Especially when the data source may be uncertain or missing, how to elegantly judge whether a variable is empty and provide a reasonable default value, which directly affects the user experience and the stability of page rendering.The AnQi CMS, with its template engine similar to Django, provides us with powerful and intuitive tools to meet these challenges.

2025-11-06

How to get the thumbnail version of the image in AnQiCMS template?

As an experienced CMS website operation personnel, I am well aware of the importance of high-quality content and excellent user experience.In the visual presentation of a website, images play a core role, and the optimization of images, especially the application of thumbnails, is invaluable for improving page loading speed, enhancing user experience, and improving search engine rankings.The AnQi CMS provides strong and flexible support in this aspect, allowing operation personnel to easily obtain and display thumbnail versions of images in templates.In today's content-driven internet environment, it has become commonplace for web pages to contain a large number of images. However

2025-11-06