How to create reusable template code snippets (macros)?

Calendar 👁️ 79

In the daily content operation of Anqi CMS, we often encounter some interface elements or code structures that need to be used repeatedly.For example, a standardized article list item, a product display card with a unified style, or a footer contact information with specific layout details.If you always write these codes manually, it is not only inefficient but also prone to inconsistent formatting issues.At this point, the "Macro" function provided by Anq CMS is particularly important, as it helps us easily create reusable template code snippets, greatly enhancing the efficiency and code quality of template development.

What is a template macro (Macro)?

Macros, in the AnQi CMS template engine (based on Django template syntax), can be understood as functions or mini-components in the template.They allow us to encapsulate a piece of HTML or code snippet with specific logic and structure, and define some parameters that can be passed in.When it is necessary to use this code, we just call the macro like a function and pass the corresponding parameters, the macro will generate predefined content according to these parameters.

Why use a template macro?

Using macros can bring many benefits:

  • Reduce duplicate code (DRY principle)Avoid copying and pasting the same code block in multiple template files to make the template more concise.
  • Improve code maintainabilityOnce the display logic or structure of a macro needs to be adjusted, it is only necessary to modify the definition file of the macro, and all references to the macro will be automatically updated without the need to modify each one individually.
  • Maintain consistency of page style: By rendering specific UI components through a unified macro, it can ensure that the visual and interactive style is consistent throughout the website.
  • improve development efficiencyOnce the macro is defined, subsequent development can directly call it, greatly shortening the development time.

How to create and use a macro?

The macro function of AnQi CMS is powerful and flexible, which can be defined and used in a single template file, or split into independent macro files for centralized management and introduction.

1. Define and use macros in the current template file

The simplest usage of macros is to define them directly at the top of the current template file or at any needed location. The definition of macros uses{% macro %}and{% endmacro %}Label wrapping, and can declare accepted parameters.

Example of macro definition:Suppose we need a unified article list card display style, including article titles and links.

{% macro article_card(article) %}
<div class="article-item">
    <h3 class="article-title"><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
    {% if article.Description %}
    <p class="article-description">{{ article.Description }}</p>
    {% endif %}
    <span class="article-date">{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
</div>
{% endmacro %}

In this example,article_cardIs the name of the macro,articleIt accepts the parameters, we expect to pass an object containing article information.

Macro call example:In the same template file, after we get the article list data, we can call the macro like this:

{% archiveList articles with type="list" limit="5" %}
    {% for item in articles %}
        {{ article_card(item) }} {# 调用上面定义的宏,传入每篇文章的数据 #}
    {% endfor %}
{% endarchiveList %}

In this way, each article will be rendered uniformly.article_cardStyle.

2. Place macros in a dedicated file separately

When the number of macros increases, or when the same macro needs to be reused in multiple template files, it is recommended to store the macro definition in a separate file. According to the template conventions of Anqi CMS, such code snippets are usually placed in the root directory of the template.partial/In the catalog.

Step 1: Create a macro fileIn your template directory (for exampletemplate/default/), create apartial/directory and create a file within it, such as_macros.htmlAn underscore prefix is a common convention indicating that this is an auxiliary file.

Inpartial/_macros.htmlDefine your macro in the file:

{# partial/_macros.html 内容 #}

{% macro article_card(article) %}
<div class="article-item">
    <h3 class="article-title"><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
    {% if article.Description %}
    <p class="article-description">{{ article.Description }}</p>
    {% endif %}
    <span class="article-date">{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
</div>
{% endmacro %}

{% macro product_thumbnail(product) %}
<div class="product-thumb">
    <a href="{{ product.Link }}">
        <img src="{{ product.Thumb }}" alt="{{ product.Title }}" loading="lazy">
        <p class="product-name">{{ product.Title }}</p>
    </a>
</div>
{% endmacro %}

Step 2: Introduce and use the macro in other templates.In your main template file (for exampleindex.htmlordetail.htmlUse it in{% import %}tags to include macro files. You can include multiple macros at once, or you can specify aliases for macros.

{# index.html 内容 #}

{% import "partial/_macros.html" article_card, product_thumbnail as thumb_macro %}

{# ... 页面其他内容 ... #}

<h2>最新文章</h2>
<div class="articles-list">
    {% archiveList latestArticles with type="list" moduleId=1 limit="3" %}
        {% for item in latestArticles %}
            {{ article_card(item) }} {# 调用 article_card 宏 #}
        {% endfor %}
    {% endarchiveList %}
</div>

<h2>推荐产品</h2>
<div class="products-grid">
    {% archiveList featuredProducts with type="list" moduleId=2 limit="4" %}
        {% for item in featuredProducts %}
            {{ thumb_macro(item) }} {# 调用 product_thumbnail 宏的别名 thumb_macro #}
        {% endfor %}
    {% endarchiveList %}
</div>

By{% import "partial/_macros.html" article_card, product_thumbnail as thumb_macro %}we included_macros.htmlfiles defined inarticle_cardandproduct_thumbnailTwo macros. One of them,product_thumbnailis assignedthumb_macroan alias for convenience in the current template.

The scope of the macro: withincludethe key difference.

It should be especially noted that macros and{% include %}tags have essential differences in variable scope.

  • {% include %}: will inherit and can directly access all variables in the parent template it calls.
  • {% macro %}It has its own independent scope.OnlyIt can access variables passed in explicitly through parameters. This means that if you have a variable in the parent template,global_settingA variable that is not passed as a parameter to the macro cannot be accessed directly within the macroglobal_setting.

This design makes macros more independent and modular, reduces unexpected variable conflicts, and also makes the reusability of macros stronger, because it does not depend on a specific external environment.

**Practice

  • Explicit naming: The name of the macro should clearly express its function or the component rendered.
  • Single Responsibility: A macro should ideally be responsible for rendering a specific component or code snippet, avoiding overly complex functionality.
  • Parameterization: Pass all possible variable elements through parameters to make the macro more flexible.
  • Store agreements: Place all macro files inpartial/the directory for easy management and search.
  • Use aliases wiselyInimportSet concise aliases for long macro names to improve readability.

By proficiently mastering the creation and application of macros, you will be able to carry out Anqi CMS template development more efficiently and elegantly, constructing high-quality websites with clear structure and easy maintenance.


Frequently Asked Questions (FAQ)

1. Can the macro access all variables on the current page?Cannot. Macros have their own scope and can only access variables explicitly passed as arguments.You must explicitly pass a variable from the parent template as a parameter to the macro if you need to use it in a macro.

2. Macro andincludeWhat is the essential difference between tags? How should I choose?The main difference lies in the scope of variables and usage scenarios: *

Related articles

How to include a common header, footer, or sidebar template file?

When building a website on Anqi CMS, we often encounter the need: the header (Header), footer (Footer), or sidebar (Sidebar) appear repeatedly on multiple pages.If you copy code every time, not only is it inefficient, but maintenance and updates will also become extremely complex. 幸运的是,AnQi CMS is developed based on Go language, its template engine supports syntax similar to Django, providing a very flexible and powerful way to introduce these public template files, helping us to achieve efficient content management and maintenance.

2025-11-09

How to define and use custom variables in a template?

In website operation, we often need to display diverse content, which may include system preset data, as well as customized personalized information based on business needs.AnQiCMS (AnQiCMS) fully understands this need, providing flexible and diverse mechanisms, allowing you to easily define and use custom variables in templates, thus achieving precise control and personalized display of content. This article will introduce you to the various methods of defining and using custom variables in AnQiCMS templates, helping you to fully utilize these features to create websites with more expressiveness and practicality.###

2025-11-09

How to implement automatic line break display for long text?

In website content operation, we often encounter situations where we need to display a large amount of text. If these long texts are not handled properly, they may exceed the designed container, causing chaos in page layout and severely affecting user experience.AnQi CMS provides us with flexible and powerful template functions, which can easily solve the display problem of long text, especially for automatic line breaks.### Core Strategy: Using the `wordwrap` filter to implement automatic text wrapping The template system of Anqi CMS is built-in with many practical filters (Filters), among which

2025-11-09

How to concatenate array elements into a string with a specified separator?

When operating a website, we often encounter the need to display a set of related data in the form of a list, such as multiple tags for articles, multiple keywords for product features, or multiple image URLs in an image library.At this time, if these scattered data elements can be integrated into a concise string and separated by specific symbols, it will greatly enhance the display effect and readability of the content.The Anqi CMS template engine provides a very practical `join` filter, which can easily meet this requirement.Understanding the `join` filter `join`

2025-11-09

How to design a basic template and allow other pages to inherit it?

Building websites in AnQi CMS, efficient and flexible template design is the key to improving development efficiency and maintaining website consistency.Among them, designing a basic template and allowing other pages to inherit it is the core strategy to achieve this goal.AnQi CMS adopts a syntax similar to the Django template engine, making template inheritance intuitive and powerful. ### Lay the Foundation: Create Your Basic Template First, let's create the basic template skeleton of a website. In Anqi CMS, all template files are stored in the `/template` directory

2025-11-09

How to display multi-language switch options for the current site?

How to easily add multilingual switching options to a website in AnQi CMS?With the continuous deepening of globalization trends, many enterprises and content operators find that having a website that supports multilingual is crucial for expanding the market and serving users in different regions.AnQi CMS understands this need, therefore it has built-in powerful multilingual support functions, allowing you to easily manage and display content in different languages. After your website content is prepared in multiple languages, the next step naturally is to provide visitors with an intuitive language switcher.This can not only improve the user experience

2025-11-09

How to add hreflang tags in templates to support multi-language SEO?

With the increasing trend of globalization, many websites are facing the challenge of providing content to users of different languages or regions.To ensure that your multilingual website performs well in search engines and accurately guides users to their preferred language version, adding the `hreflang` tag is crucial.AnQiCMS (AnQiCMS) is an enterprise-level content management system that deeply supports multilingualism and provides a convenient way to implement this feature in templates.### Understand the role of the hreflang tag `hreflang`

2025-11-09

How to display the list of dynamic Banner images configured in the website?

The website's banner area, like a dynamic promotional window, its visual appeal and content delivery efficiency directly affect the first impression of visitors to the website.A well-designed Banner that can quickly capture the user's attention and effectively showcase the brand image, latest activities, or core products.In AnQiCMS (AnQi CMS), by utilizing its powerful content management features, you can easily configure and display a dynamic banner image list, keeping your website fresh and attractive.###

2025-11-09