How to define and call the `macro` tag in AnQiCMS template to display reusable code blocks?

Calendar 👁️ 68

AnQiCMS provides a flexible and powerful template system that allows the display of website content to be both efficient and beautiful.In template development, in order to improve code reuse and maintainability, we often encounter the need to encapsulate a frequently used code snippet for calling in different places.macroLabels become the key tools to achieve this goal. They allow us to define reusable code blocks, just like functions in programming languages.

Why is it neededmacroTag?

Imagine if your website has multiple content types, such as article lists, product showcases, which may have some common elements in layout, such as a title, a brief introduction, and an image.If you have to rewrite the HTML structure of these elements each time, it is not only inefficient, but also once you need to modify the style or structure, you have to search and update all the places one by one, which undoubtedly brings huge maintenance costs.

macroThe appearance of tags is to solve such problems.It allows you to encapsulate these repeated HTML structures along with their logic (such as how to display an article title, how to format dates) into an independent, callable code block.This allows you to define it once and then call it multiple times anywhere in the template, greatly enhancing the modularity, readability, and maintainability of the template code.

How do you define amacrocode block?

In AnQiCMS templates, definemacrothe syntax is very intuitive, it is similar to defining a function:

{% macro macro_name(parameter1, parameter2, ...) %}
    {# 这里是可复用的代码块,可以使用传入的参数 #}
{% endmacro %}

macrotags to{% macro ... %}and ends with{% endmacro %}End. You need to specify a unique name for thismacrosuch asarticleItem), and list the parameters it will accept. These parameters are like the inputs of a function.macroThe internal code can only access the variables passed in by these parameters.

For example, let's define a macro for displaying article list items.macro:

{# 定义一个名为 "articleItem" 的宏,接受一个名为 "article" 的参数 #}
{% macro articleItem(article) %}
    <li class="article-card">
        <a href="{{ article.Link }}" title="{{ article.Title }}">
            <div class="card-image">
                {% if article.Thumb %}<img src="{{ article.Thumb }}" alt="{{ article.Title }}"/>{% endif %}
            </div>
            <h3 class="card-title">{{ article.Title }}</h3>
            <p class="card-description">{{ article.Description|truncatechars:80 }}</p>
            <div class="card-meta">
                <time>{{ stampToDate(article.CreatedTime, "2006-01-02") }}</time>
                <span>阅读量: {{ article.Views }}</span>
            </div>
        </a>
    </li>
{% endmacro %}

In this example,articleItemThe macro accepts onearticleobject as a parameter. Inside the macro, we usearticle.Link/article.Titleto access the properties of the passed article object, and usetruncatecharsUse to filter the descriptionstampToDateFormat the time.

Call the definedmacroCode block

DefinedmacroAfter that, calling it is very simple. You can call it in the same template file by the following method:

{# 假设我们使用 archiveList 标签获取了一系列文章数据 #}
{% archiveList articles with type="list" limit="5" %}
    <ul class="article-list">
    {% for item in articles %}
        {# 调用前面定义的 articleItem 宏,并传入当前循环的文章对象 #}
        {{ articleItem(item) }}
    {% endfor %}
    </ul>
{% empty %}
    <p>暂时没有文章内容。</p>
{% endarchiveList %}

Here, we are in aforloop, we called aarticleItemmacro, each iteration will take the currentitem(That is, an article object is passed as a parameter to the macro. The macro will generate the corresponding HTML structure according to its definition.)

Cross-file reusemacro:importpower

For large projects, all themacroAll defined in one file will soon become difficult to manage. AnQiCMS allows you tomacrodefined in separate files and throughimportTag it to the template where it needs to be used, achieving true file reuse across files.

  1. Create a macro file: Generally, we would create a dedicated directory (such as_macrosorpartials/macros) to store all macro files. Suppose we create a file named_macros/article_card.htmland define the abovearticleItemmacro:

    {# 文件路径: templates/your_theme/_macros/article_card.html #}
    {% macro articleItem(article) %}
        <li class="article-card">
            <a href="{{ article.Link }}" title="{{ article.Title }}">
                <div class="card-image">
                    {% if article.Thumb %}<img src="{{ article.Thumb }}" alt="{{ article.Title }}"/>{% endif %}
                </div>
                <h3 class="card-title">{{ article.Title }}</h3>
                <p class="card-description">{{ article.Description|truncatechars:80 }}</p>
                <div class="card-meta">
                    <time>{{ stampToDate(article.CreatedTime, "2006-01-02") }}</time>
                    <span>阅读量: {{ article.Views }}</span>
                </div>
            </a>
        </li>
    {% endmacro %}
    
    {# 如果有其他宏,也可以一同在此文件中定义 #}
    {% macro productCard(product) %}
        <li class="product-card">
            {# ... 产品卡片结构 ... #}
        </li>
    {% endmacro %}
    
  2. in other templates and use: Inindex.htmlOr any template file that needs to use these macros, you can useimportto introduce them:

    {# 文件路径: templates/your_theme/index.html #}
    {% import "_macros/article_card.html" articleItem, productCard as myProductCardMacro %}
    
    <h1>最新文章</h1>
    {% archiveList articles with type="list" limit="5" %}
        <ul class="article-list">
        {% for item in articles %}
            {{ articleItem(item) }} {# 调用导入的 articleItem 宏 #}
        {% endfor %}
        </ul>
    {% endarchiveList %}
    
    <h1>推荐产品</h1>
    {% archiveList products with moduleId="2" type="list" limit="3" %}
        <ul class="product-list">
        {% for item in products %}
            {{ myProductCardMacro(item) }} {# 调用导入并设置别名的 productCard 宏 #}
        {% endfor %}
        </ul>
    {% endarchiveList %}
    

    ByimportWe can import one or more macros at a time. Use comma,to separate multiple macros

Related articles

How to avoid extra blank lines when template logical tags (such as if, for) are rendered on the page?

When developing templates in AnQiCMS, we often find that even though the template code itself looks neat, the final rendered HTML page may still contain some unexpected blank lines.These blank lines do not affect the page function, but may make the HTML source code look less tidy, and even in some extreme optimization scenarios, it may bring a slight increase in file size.For users who pursue code aesthetics and concise output, how to effectively avoid these redundant blank lines is a topic worth discussing.

2025-11-08

How to loop through a list of data in a template and display it (using for loop), supporting counting and reversing?

In Anqi CMS template, efficiently displaying list data is an indispensable part of website content operation.Whether it is to display the latest articles, product lists, category directories, or customized data sets, flexible looping through these data and fine-grained control can greatly enhance the performance and user experience of the website.The Anqi CMS provides a powerful and easy-to-use template engine, its `for` loop tag is rich in features, supporting not only basic iteration but also easily implementing counting, reversal, and more advanced operations.### Core Concept: `for`

2025-11-08

How to implement conditional (if/else) dynamic display of content and layout in a template?

In website operations and frontend development, we often need to flexibly display content or adjust the page layout according to different situations.This dynamic ability is the core value of the conditional judgment tag (`if/else`) in AnQiCMS templates.The Anqi CMS template engine is simple and powerful, allowing us to set logic on the page like writing program code, making the website content show endless possibilities.### The Dynamic Beauty of AnQi CMS Template

2025-11-08

How to customize the display template for specific articles, categories, or single pages to achieve personalized layout?

In website operation, providing exclusive display methods for specific content can significantly improve user experience and content marketing effectiveness.AnQiCMS (AnQiCMS) is well-versed in this field, providing flexible and diverse template customization features, allowing you to easily create a unique personalized layout for articles, categories, or single pages. The AnQi CMS realizes personalized template customization in two main ways: one is to follow specific **template file naming conventions**, the system will automatically identify and apply;Secondly, it is manually specified in the background management interface to use a custom template file.--- ### One

2025-11-08

How to optimize page layout and content display by using the template inheritance (`extends`) tag?

In AnQiCMS, templates are the foundation for building the appearance and layout of a website.A well-designed template not only makes the website look professional and beautiful, but also greatly enhances the efficiency of content operation and the convenience of website maintenance.Among many powerful template tags, the `extends` (template inheritance) tag is undoubtedly one of the key tools for optimizing page layout and content display.It can help us build a unified and flexible website structure, making content operation and frontend development more effortless.### Understanding `extends`: The core of template inheritance `extends`

2025-11-08

How to declare a temporary variable in AnQiCMS template and use it to display content, improving template flexibility?

In the template creation of Anqi CMS, we often need to display various dynamic content.It is crucial to be proficient in using temporary variables to make templates more flexible and code more concise.The Anqi CMS template engine provides powerful functionality for declaring temporary variables, which helps us better organize and process data, thereby improving the efficiency and maintainability of content display.### Understanding the Value of Temporary Variables Imagine that you need to display processed data at multiple locations on the page, or that a piece of data is used repeatedly in conditional judgments, or that data obtained from a tag needs to be further processed before it can be presented

2025-11-08

How to obtain and display the title and detailed content on the article detail page?

Manage website content in Anqi CMS, the article detail page is an important window for displaying core information to visitors.Whether it is corporate news, product introduction, or technical articles, clearly presenting the title and detailed content is the key to improving user experience and information communication efficiency.The Anqi CMS provides intuitive and powerful template tags, making content presentation easy and flexible. ### Understanding Anqi CMS Template Structure Anqi CMS template files are usually stored in the `/template` directory and follow a set of simple naming conventions.for the detail page of an article or product document

2025-11-08

How to correctly display images in the article content of AnQiCMS templates and support lazy loading of images?

In content operation, exquisite images can significantly enhance the attractiveness and reading experience of articles.However, image files are often large, and if not handled properly, they may slow down page loading speed, affect user experience, and even search engine rankings.AnQiCMS fully understands this, providing a flexible way to correctly display images in article content within templates, and supports lazy loading of images to balance aesthetics and performance.### Core: Display images in article content In the AnQiCMS template, to obtain the main content of the article, we mainly rely on `{%

2025-11-08