How can you correctly import and use multiple `macro` functions defined in different files?

Calendar 👁️ 66

As an experienced website operations expert, I deeply understand the importance of the neat, efficient, and maintainable template code for the long-term operation of the website. In a flexible and powerful content management system like AnQiCMS, it is important to fully utilize its template engine features, especially macro functions (macroIt can greatly enhance development efficiency and the quality of content display. Today, let's delve into how when you define multiple in different filesmacroHow to cleverly import and utilize functions.


Unlock the potential of templates: Efficiently import and use macros in Anqi CMS.

in the AnQi CMS template world,macroMacros are like a Swiss Army knife in your toolbox, allowing you to define reusable code snippets and pass parameters as if calling a function to generate dynamic content.This mechanism greatly reduces code redundancy and improves the cleanliness and maintainability of the template.

Macro functions: The concept of 'functions' in templates.

In simple terms, a macro function is a named block of template code that can accept parameters and return specific HTML or text content.You can encapsulate any UI element or data display logic that repeats into a macro.For example, a single article card in an article list, a specification display area on a product detail page, or a unified form input box, can all be implemented through macro functions.

Define a macro functionThe syntax is very intuitive:

{% macro macro_name(parameter1, parameter2, ...) %}
    {# 宏函数的内容,可以使用传入的参数 #}
    <div class="my-component">
        <h3>{{ parameter1 }}</h3>
        <p>{{ parameter2 }}</p>
    </div>
{% endmacro %}

here,macro_nameThe name of the macro, inside the parentheses are the parameters it accepts.{% macro %}and{% endmacro %}Between them, you can write any template code and use the passed parameters to dynamically generate content.

Why do we need macro functions?

Imagine, your website has dozens of pages, each of which needs to display a similar product card or article summary.If there is no macro function, you may need to write almost the same HTML structure and data binding logic on each page.This takes time and once there is a minor change in design or data structure, you need to manually modify it in all related files, which is undoubtedly an operation nightmare.

The introduction of macro functions, perfectly solves these pain points:

  1. Code reuse:Once defined, called multiple times, avoiding redundant work.
  2. Maintenance convenience:Just modify the definition of the macro function, and all the places that call it will be automatically updated.
  3. to enhance readability:The template code becomes more concise, focusing only on the overall layout of the page, and hiding the details of complex components in macro functions.
  4. Team collaboration:Different developers can focus on developing different macro functions and then easily integrate them.

Organize your macro function files.

In order to maintain the neatness and structured of template code, we usually place these reusable macro definitions in the template directory or create one inside.partial/folder, or create one inside.macros/Subfolder. For example, you can create a file namedpartial/_common_macros.htmlto store the website's general macro functions, or divide according to functional modules, such aspartial/_article_macros.html/partial/_product_macros.htmletc.

This clear file organization method allows you and your team to quickly locate, understand, and manage the definition of macro functions.

Import macro function: connect different files

Once you have defined a macro function in a separate template file, the next step is to import it on the page where you need to use it. The Anqi CMS template engine providesimportTag to implement this feature.

basic import syntaxAs follows:

{% import "file_path" macro_name %}

Herefile_pathIs the file path where you define the macro function, which is usually a relative path to the current template root directory. For example, if_common_macros.htmlis locatedpartial/directory, then the path is"partial/_common_macros.html".

import multiple macro functions

If you define multiple macro functions in a macro file, you can optionally import one, several, or even all of them.

  1. Import a single macro function:

    {% import "partial/_common_macros.html" my_single_macro %}
    
  2. Import multiple macro functions (comma-separated):

    {% import "partial/_common_macros.html" macro1, macro2, another_macro %}
    
  3. Set alias for macro functions (asKeyword):When the name of the macro function you import may conflict with the variable name in the current template, or when you want to use a simpler and easier-to-remember name,askeywords come into play.

    {% import "partial/_common_macros.html" original_macro_name as my_alias %}
    

    You can also import multiple macros at once and set aliases:

    {% import "partial/_common_macros.html" macro1, macro2 as second_macro_alias %}
    

    By alias, you can clearly distinguish macros from different sources and avoid potential naming conflicts, which is particularly important in large projects.

Use imported macro functions

After importing the macro function, use it as a regular function. Just use double curly braces.{{ }}Wrap the macro function name and its required parameters.

{# 假设您在 partial/_common_macros.html 中定义了一个名为 'render_card' 的宏 #}
{# 并传入了文章标题和摘要作为参数 #}
{{ render_card(article.Title, article.Description) }}

A comprehensive example.

Let's go through a simple scenario to tie the entire process together: we need to display the summary information card of the article uniformly on the home page and the category list page.

1. Atpartial/_article_macros.htmlDefine macros in:

{# partial/_article_macros.html #}
{% macro article_summary_card(article_obj) %}
    <div class="article-card">
        <a href="{{ article_obj.Link }}">
            {% if article_obj.Thumb %}<img src="{{ article_obj.Thumb }}" alt="{{ article_obj.Title }}"/>{% endif %}
            <h4>{{ article_obj.Title }}</h4>
        </a>
        <p>{{ article_obj.Description|truncatechars:100 }}</p>
        <div class="meta">
            <span>{{ stampToDate(article_obj.CreatedTime, "2006-01-02") }}</span>
            <span>阅读量: {{ article_obj.Views }}</span>
        </div>
    </div>
{% endmacro %}

{% macro other_utility_macro(text) %}
    <p>这是一个辅助宏: {{ text }}</p>
{% endmacro %}

2. Inindex.html(or)archive/list.htmlImport and use macro:

{# index.html 或 archive/list.html #}
{% extends "base.html" %} {# 继承基础模板 #}

{# 导入文章摘要卡片宏和另一个辅助宏 #}
{% import "partial/_article_macros.html" article_summary_card, other_utility_macro as helper_text_macro %}

{% block content %}
    <div class="main-content">
        <h2>最新文章</h2>
        <div class="article-list">
            {% archiveList latest_articles with type="list" limit="6" order="id desc" %}
                {% for article in latest_articles %}
                    {# 调用导入的宏函数来渲染每篇文章卡片 #}
                    {{ article_summary_card(article) }}
                {% empty %}
                    <p>暂无文章。</p>
                {% endfor %}
            {% endarchiveList %}
        </div>

        {# 使用别名导入的辅助宏 #}
        {{ helper_text_macro("网站内容正在持续更新中!") }}
    </div>
{% endblock %}

Through this example, we can clearly see that by defining macro functions in a separate file and by using them,importLabel it flexibly and use it, our template code becomes extremely tidy and efficient.

**Practical Suggestions

  • Maintain the focus of the macro:Each macro function should focus on a single responsibility and avoid having too many functions in one macro function.
  • Clear naming:The naming of macro functions and their parameters should be descriptive, making it easy for people to understand their purpose at a glance.
  • Centralized management:Develop the habit of placing all macro function files in a specific directory (such aspartial/macros/)

Related articles

How does a `macro` tag-defined code snippet receive and process external variables or parameters?

The AntQue CMS template tool: how to elegantly handle external parameters with `macro` tag?In AnQiCMS template development, to improve code reusability and maintainability, we often use some auxiliary tags, and one particularly powerful and worth in-depth exploration is the `macro` tag.It is like a function in a programming language, allowing us to define reusable code snippets and customize their behavior by passing in different parameters when needed. Today

2025-11-07

In AnQi CMS template, how to define a reusable custom function or code snippet (such as looping to render article list items)?

Behind the powerful functions of AnQi CMS, the flexible use of templates is the key to improving efficiency and ensuring website consistency.As an experienced website operations expert, I know that in daily work, we always hope to achieve 'efforts for twice the results'.Today, let's delve deeply into a topic that can greatly enhance the efficiency of template development and maintenance: how to define and use reusable custom functions or code snippets in Anqi CMS templates, especially for common scenarios like looping to render article list items.Why do we need reusable code snippets?In the digital age, content is king

2025-11-07

Does the `include` tag support dynamic filenames, i.e., deciding which template file to include based on the variable value?

## Unveiling the `include` tag of AnQi CMS: Can the dynamic template filename work?As a senior website operations expert, I have a deep understanding of the template mechanism of the content management system (CMS).In the daily use and deep customization of AnQiCMS (AnQiCMS), the flexibility and efficiency of the template are one of the key factors determining the success or failure of website operations.

2025-11-07

In the AnQi CMS template, what are the advantages of the `include` tag compared to the traditional copy and paste method?

## Say goodbye to the繁琐repetition: The art and efficiency of the `include` tag in Anqi CMS templates Efficiency and maintainability are key factors in determining the success or failure of modern website operations.As an experienced website operation expert, I am well aware of how an excellent content management system (CMS) silently supports the brilliant presentation of the frontend in the background.

2025-11-07

What are the core differences between `macro` tags and `include` tags in terms of variable scope and code reuse?

As an experienced website operation expert, I have a deep understanding of the powerful functions and content operation strategies of AnQiCMS (AnQi CMS).AnQi CMS, with its efficient architecture based on the Go language, flexible content model, and friendly support for SEO, has become the preferred tool for many small and medium-sized enterprises and content operation teams.In template development, how to efficiently and safely reuse code is the key to improving operational efficiency, and `macro` tags and `include` tags are the two powerful tools to achieve this goal.

2025-11-07

How to set an alias for the imported `macro` function to avoid naming conflicts in large projects?

As an experienced website operation expert, I am well aware that how to elegantly manage and reuse template code in an efficient and flexible content management system like AnQiCMS is the key to improving project efficiency and maintainability.The AnqCMS based on Go language and Django template engine syntax provides us with powerful template tag functions, among which the `macro` function is a tool for code reuse.

2025-11-07

What are the advantages of using the `macro` tag when building complex or nested UI components compared to writing logic directly on the page?

In modern website operations, efficiency and flexibility are the key to success.When it comes to building a feature-rich, complex website, how to efficiently manage and maintain a large number of UI components is a great challenge facing website operators and front-end developers.AnQiCMS (AnQiCMS) is an enterprise-level content management system developed based on the Go language, deeply understanding this field, its powerful template engine and various auxiliary tags are exactly designed to solve these pain points.

2025-11-07

Can the `macro` function call other already imported or defined `macro` functions within it?

## The Mystery of Nested Macro Function Calls in AnQiCMS Templates: Building Efficient and Maintainable Front-end Code In the daily operation and template development of AnQiCMS (AnQiCMS), we often make use of its powerful and flexible template engine to construct dynamic content.Among them, the `macro` function has become a powerful tool for front-end developers due to its code reuse capability.It allows us to define reusable code snippets, like functions that accept parameters and return rendered HTML.

2025-11-07