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

As an experienced website operations expert, I know that the neatness, efficiency, and maintainability of template code are crucial for the long-term operation of a website. In a flexible and powerful content management system like AnQiCMS, it is important to make full use of its template engine features, especially macro functions (macro),can greatly enhance the development efficiency and the quality of content display. Today, let's delve into it further, when you define multiple in different files.macroFunctions, how to ingeniously import and utilize them.


Unlock the potential of templates: Efficiently import and use macro functions in Anqi CMS

In the template world of AnQi CMS,macro(Macro function)is like a Swiss Army knife in your tool box, it allows you to define reusable code snippets and pass parameters to them as if calling a function, thus generating dynamic content.This mechanism greatly reduces code redundancy and improves the cleanliness and maintainability of the template.

Macro functions: The 'function' concept in templates

In simple terms, a macro function is a named block of template code that accepts parameters and can 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 realized 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_nameIs the name of the macro, within 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 you need macro functions?

Imagine that 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 repeat almost the same HTML structure and data binding logic on each page.This is time-consuming, and once there is a slight change in design or data structure, you need to manually modify it in all related files, which is undoubtedly an operational nightmare.

The introduction of macro functions perfectly solves these pain points:

  1. Code reuse:Once defined, used multiple times, avoiding redundant work.
  2. Maintenance convenient:Only modify the definition of the macro function, and all the places that call it will be automatically updated.
  3. Improve 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 the development of different macro functions and then easily integrate them.

Organize your macro function files

To maintain the cleanliness and structuralization of template code, we usually place these reusable macro definitions uniformly in the template directory underpartial/a folder, or create another one inside itmacros/The subfolder. For example, you can create a folder namedpartial/_common_macros.htmlThe file, which is used to store the general macro functions of the website, or divided 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 functions: connect different files

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

Basic import syntaxAs follows:

{% import "file_path" macro_name %}

Here are thefile_pathIs the file path where you define the macro function, usually a relative path to the current template root directory. For example,_common_macros.htmlis locatedpartial/Under the directory, 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 function (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 more concise and memorable 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 %}
    

    Through aliases, you can clearly distinguish different sources of macros and avoid potential naming conflicts, which is particularly important in large projects.

Use imported macro functions

Import macro functions and use them as regular functions. 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 link the entire process: we need to display the summary information card of the article uniformly on the homepage and the category list page.

1. Inpartial/_article_macros.htmldefine the macro:

{# 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.html) Import and use the 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 the macro function in a separate file and byimportLabels are imported and used flexibly, making our template code exceptionally neat and efficient.

**Practical Suggestions

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