How can the `macro` macro function in AnQiCMS templates help me reduce redundant rendering logic?

In the template development of AnQi CMS, improving efficiency and maintaining code cleanliness is the goal that every developer is pursuing.The website page often contains many areas with similar structures but different contents, such as each article card in the article list, the various characteristics display on the product detail page, or each link item in the navigation menu.If you have to repeatedly write this similar rendering logic, it not only takes time and effort, but also, once you need to make modifications, you may face the dilemma of having to make repetitive changes in multiple places.macroMacros function, which can effectively help us solve this problem and greatly reduce redundant rendering logic.

What ismacroMacros function?

In simple terms,macroMacro functions are like reusable “gadgets” or “subroutines” that you define in a template.It allows you to encapsulate a section of HTML code with specific logic and structure, and you can pass different data parameters to it like calling a function, thus rendering dynamic and expected content.macroA manifestation of its flexible and powerful functions.

WithincludeTags (used to include static or general template fragments) differ,macroMacro functions are more focused onencapsulation of dynamic content and logic.It can accept parameters and generate different content based on these input parameters, which makes it particularly efficient in handling scenarios with high repetition but varying details each time.

Why to usemacroMacros function?

ApplicationmacroMacro functions can bring significant advantages in many aspects:

  1. Reduce duplicate code:This is the most direct benefit. Defining repetitive template structures as macros avoids pasting the same code blocks in multiple places, greatly reducing the size of the template file.
  2. Improve development efficiency:Once a macro is defined, it can be quickly called at any place needed, saving time on rewriting and debugging similar code.
  3. Simplify the template structure:The main template code will become more concise and readable. Complex rendering logic is encapsulated in macros, and the main template only needs to focus on the invocation of macros and data transmission, making the logical hierarchy clearer.
  4. Easy to maintain and update:When you need to modify the display logic or style of a general UI component, you only need to modify the macro definition once, and all the places that call the macro will be automatically updated, avoiding issues of omission and inconsistency.
  5. Ensure consistency:Ensure that all elements using the same macro on the site maintain a unified structure and basic style, enhancing user experience and brand image.

AnQiCMS 中macroThe usage method

MastermacroThe usage is not complicated, mainly divided into definition and calling two steps.

1. DefinitionmacroMacro function

You can define one in any template filemacro. Usually, we would define commonly used macro functions in a separate file (for example_macros.htmlorhelpers.html), to keep the main template clean. DefinitionmacroThe basic syntax is as follows:

{% macro macro_name(参数1, 参数2, ...) %}
    {# 宏函数内部的渲染逻辑,可以使用传入的参数 #}
    <div class="some-element">
        <h2>{{ 参数1.title }}</h2>
        <p>{{ 参数2.description }}</p>
        {# 更多逻辑 #}
    </div>
{% endmacro %}

For example, we want to render a uniform card style for each article on the website, which can be defined like thisarchive_cardMacro:

{# 文件名: _macros.html #}
{% macro archive_card(item) %}
    <div class="article-card">
        <a href="{{ item.Link }}">
            {% if item.Thumb %}
                <img src="{{ item.Thumb }}" alt="{{ item.Title }}" class="card-thumbnail">
            {% endif %}
            <h3 class="card-title">{{ item.Title }}</h3>
        </a>
        <p class="card-description">{{ item.Description|truncatechars:100 }}</p>
        <div class="card-meta">
            <span>{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
            <span>阅读量:{{ item.Views }}</span>
        </div>
    </div>
{% endmacro %}

Thisarchive_cardA macro accepts a name calleditemThe parameter, which is usually an article object, includes the title, link, thumbnail, description, creation time, and reading volume of the article.

2. CallmacroMacro function

After defining a macro, you can call it in other template files. If the macro is defined in the current file, you can call it directly; if defined in other files, you need to call it first throughimportLabel import.

Call within the same file:

{# 假设 archive_card 宏定义在此文件的上方 #}
{% for archive in archives %}
    {{ archive_card(archive) }}
{% endfor %}

Import and call external macros:

This is usually recommended as it promotes the modularization of templates.

First, make sure your macro function (such as the one defined above) is saved in a separate template file, such asarchive_cardtemplates/partials/my_macros.html.

Then, in your main template file (for example)index.htmlorcategory_list.html), useimportinclude it using the tag:

{# 文件名: index.html #}
{% import "partials/my_macros.html" as my_macros %}

{# 现在你可以通过 my_macros.archive_card 来调用宏了 #}
<div class="article-list">
    {% archiveList archives with type="page" limit="10" %}
        {% for archive in archives %}
            {{ my_macros.archive_card(archive) }}
        {% empty %}
            <p>目前没有文章。</p>
        {% endfor %}
    {% endarchiveList %}
</div>

Passas my_macrosWe have given an alias to the macro file we importedmy_macrosSo, when callingarchive_cardyou need to write it asmy_macros.archive_card(archive). You can also directly import macro functions, or give an alias to the imported macro functions:

{# 导入单个宏函数 #}
{% import "partials/my_macros.html" archive_card %}
{{ archive_card(archive) }}

{# 导入并给宏函数起别名 #}
{% import "partials/my_macros.html" archive_card as custom_card %}
{{ custom_card(archive) }}

{# 导入多个宏函数并起别名 #}
{% import "partials/my_macros.html" archive_card, other_macro as om %}
{{ archive_card(archive) }}
{{ om(data) }}

PassmacroBrings actual value

Master and applymacroMacros, not just about writing less code.It can elevate template development to a more efficient and structured level.This means that in the actual operation of the website, you can respond faster to design changes, easily test and deploy new features, and ensure consistency in the visual and functional modules of the website.macroCan make you twice as effective.

In short, the Anqi CMS ismacroThe macro function is a powerful tool that encourages the modularization and reusability of templates, ultimately helping us build high-quality websites that are easier to manage, maintain, and extend.


Common Questions and Answers (FAQ)

  1. macroThe macro function andincludeWhat is the difference between tags? macroMacros can accept parameters and dynamically render content based on the parameters passed in, similar to the role of programming languages in.