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

Calendar 👁️ 66

In Anqi CMS template development, improving efficiency and maintaining code cleanliness is the goal of every developer.web pages often contain many regions with similar structures but different contents, such as each article card in the article list, the various characteristics of the product details page, or each link item in the navigation menu.If you keep writing similar rendering logic over and over, not only will it take a lot of time and effort, but you may also face the dilemma of having to make repetitive changes in multiple places. 幸运的是,AnQiCMS强大的模板系统提供了macroThe macro function, which can effectively help us solve this problem, greatly reduces the repetitive rendering logic.

What ismacroWhat is the macro function?

In simple terms,macroMacros are like reusable "gadgets" or "subroutines" you define in a template.It allows you to encapsulate a segment of HTML code with specific logic and structure, and can be called like a function to pass different data parameters, thereby rendering dynamic and expected content.The template engine syntax of AnQiCMS is similar to Django, and it is very easy for developers to get started with it,macroIt is a reflection 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 logicIt can accept parameters and generate different content based on these parameters, making it particularly efficient in handling scenarios with high repetition but varying details each time.

Why to usemacroWhat is the macro function?

applymacroMacro functions, which can bring significant advantages in many aspects:

  1. Reduce duplicate code:This is the most direct benefit. Defining repeated template structures as macros avoids pasting the same code block in multiple places, greatly reducing the volume of template files.
  2. Improve development efficiency:Once a macro is defined, it can be quickly invoked anywhere, 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 calling macros and passing data, with clearer logical levels.
  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 calling the macro will be automatically updated, avoiding omissions and inconsistencies.
  5. Ensure consistency:Ensure that all elements using the same macro on the website maintain a unified structure and basic style, enhancing user experience and brand image.

AnQiCMS inmacroUsage method

MastermacroThe usage is not complex, mainly divided into definition and invocation two steps.

1. DefinitionmacroMacro function

You can define one in any template file.macro. Usually, we 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 as followsarchive_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_cardThe 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 the macro, you can call it in other template files. If the macro is defined in the current file, you can call it directly; if it is defined in other files, you need to 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 the recommended approach, 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_cardThen, in your main template file (for exampletemplates/partials/my_macros.html.

tag it in:index.htmlorcategory_list.htmlUse it inimport:

{# 文件名: 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>

Byas my_macrosWe have given an alias to the imported macro filemy_macrosSo, when callingarchive_cardyou need to write it asmy_macros.archive_card(archive)You can also directly import the macro function, or give an alias to the imported macro function:

{# 导入单个宏函数 #}
{% 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) }}

BymacroThe actual value brought

Master and applymacroMacros are not just about writing less code. They can elevate template development to a more efficient and structured level.In the operation of actual websites, this means you can respond faster to design changes, make it easier to test and deploy new features, and ensure the visual and functional consistency of the various modules of the website.Whether it is to deal with SEO details adjustment, or to fine-tune the UI interface,macroCan make you twice the work with half the effort.

In short, the Anqi CMS'smacroMacros are 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 scale.


Frequently Asked Questions (FAQ)

  1. macromacro functions andincludeWhat are the differences between tags? macroMacros can accept parameters and dynamically render content based on the parameters passed in, serving a similar function to programming languages in

Related articles

How to pass specific variables or data when including a sub-template?

Advanced AnQiCMS Template: `include` Sub-template Data Passing Techniques and Practices In AnQiCMS template development, the `include` tag is undoubtedly a powerful tool for enhancing template reusability and modularization.It allows us to extract common code snippets (such as page headers, footers, sidebars, etc.) and then introduce them where needed, thus avoiding repetition and making the template structure clearer and maintenance more efficient.However, the sub-templates introduced often need to display different content, which raises a core question: how to introduce sub-templates at the time

2025-11-08

How to use the `include` tag to reuse header, footer, and other common code segments in AnQiCMS templates?

Building website templates in AnQiCMS, efficient code reuse is the key to improving development speed and maintenance efficiency.Imagine, the header (Header) and footer (Footer) of a website appear almost on every page. If the same code is written on each page, it is not only time-consuming, but also, once a modification is needed, it has to be searched and updated on each page, which is undoubtedly a huge amount of work.

2025-11-08

How to safely output content containing HTML tags in AnQiCMS templates (e.g., article content)?

Guide to safely output HTML content in AnQiCMS templates When building a website with AnQiCMS, we often need to display content with rich formatting, such as article content, product descriptions, category details, or single-page content.This content is usually entered through the backend rich text editor, which will naturally contain HTML tags such as `<p>`, `<strong>`, `<em>`, `<a>`, and so on.How to correctly and safely output this content with HTML tags in the front-end template is a very important issue.If handled improperly

2025-11-08

How to alternate different CSS classes or styles while looping through list items?

In web design, to enhance visual aesthetics and user experience, we often encounter situations where we need to alternate different CSS classes or styles for list items (such as article lists, product lists, navigation menus, etc.).For example, make the background color of odd and even rows different, or apply a unique layout style every few items.AnQiCMS (AnQiCMS) leverages its flexible template engine to provide a variety of simple and efficient methods to meet this requirement.

2025-11-08

What role does the `extends` tag play in the AnQiCMS template inheritance system?

In AnQiCMS template development, the `extends` tag plays a core role, it is the key to building efficient, maintainable and structurally unified website templates.The `extends` tag can be understood as creating a bridge between 'master' and 'child pages', allowing you to easily define a common layout skeleton for the entire website without repeating a lot of the same code on each page.

2025-11-08

How to output the current date and time in the AnQiCMS template and specify the format?

Displaying the date and time in the AnQiCMS template in a specific format is a common requirement in website content operations.Whether it is to display the publication time of articles, the deadline of events, or show the current year in the footer, accurate and beautiful time information can enhance the user experience.AnQiCMS provides simple and efficient template tags, allowing you to easily implement these features. Next, we will discuss in detail how to output the current date and time in the AnQiCMS template and specify the format you need.

2025-11-08

How to output variables in a template and safely escape content to prevent XSS attacks?

In the process of managing and displaying website content, ensuring the security of user data is a crucial link.It is an issue that every website operator needs to pay attention to when the website needs to display user submitted content or data obtained from external sources, how to effectively prevent cross-site scripting (XSS) attacks.AnQiCMS (AnQiCMS) took this into full consideration from the very beginning, providing solid security guarantees for content output through its powerful template engine and flexible filter mechanism.### Cross-Site Scripting Attack

2025-11-08

How to display the latest N articles or products on the homepage and implement pagination control?

## Asecurity CMS: The Practice of Efficiently Displaying the Latest Content on the Homepage and Implementing Pagination The homepage is an important entry point for visitors to understand the site content and obtain the latest information, it is crucial to clearly and effectively display the latest published articles or products.The AnQi CMS provides powerful and flexible template tags, which help us easily achieve this goal, and can also fine-tune content pagination to ensure a smooth user experience.

2025-11-08