In the daily content operation of Anqi CMS, we often encounter some interface elements or code structures that need to be used repeatedly.For example, a standardized article list item, a product display card with a unified style, or a footer contact information with specific layout details.If you always write these codes manually, it is not only inefficient but also prone to inconsistent formatting issues.At this point, the "Macro" function provided by Anq CMS is particularly important, as it helps us easily create reusable template code snippets, greatly enhancing the efficiency and code quality of template development.
What is a template macro (Macro)?
Macros, in the AnQi CMS template engine (based on Django template syntax), can be understood as functions or mini-components in the template.They allow us to encapsulate a piece of HTML or code snippet with specific logic and structure, and define some parameters that can be passed in.When it is necessary to use this code, we just call the macro like a function and pass the corresponding parameters, the macro will generate predefined content according to these parameters.
Why use a template macro?
Using macros can bring many benefits:
- Reduce duplicate code (DRY principle)Avoid copying and pasting the same code block in multiple template files to make the template more concise.
- Improve code maintainabilityOnce the display logic or structure of a macro needs to be adjusted, it is only necessary to modify the definition file of the macro, and all references to the macro will be automatically updated without the need to modify each one individually.
- Maintain consistency of page style: By rendering specific UI components through a unified macro, it can ensure that the visual and interactive style is consistent throughout the website.
- improve development efficiencyOnce the macro is defined, subsequent development can directly call it, greatly shortening the development time.
How to create and use a macro?
The macro function of AnQi CMS is powerful and flexible, which can be defined and used in a single template file, or split into independent macro files for centralized management and introduction.
1. Define and use macros in the current template file
The simplest usage of macros is to define them directly at the top of the current template file or at any needed location. The definition of macros uses{% macro %}and{% endmacro %}Label wrapping, and can declare accepted parameters.
Example of macro definition:Suppose we need a unified article list card display style, including article titles and links.
{% macro article_card(article) %}
<div class="article-item">
<h3 class="article-title"><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
{% if article.Description %}
<p class="article-description">{{ article.Description }}</p>
{% endif %}
<span class="article-date">{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
</div>
{% endmacro %}
In this example,article_cardIs the name of the macro,articleIt accepts the parameters, we expect to pass an object containing article information.
Macro call example:In the same template file, after we get the article list data, we can call the macro like this:
{% archiveList articles with type="list" limit="5" %}
{% for item in articles %}
{{ article_card(item) }} {# 调用上面定义的宏,传入每篇文章的数据 #}
{% endfor %}
{% endarchiveList %}
In this way, each article will be rendered uniformly.article_cardStyle.
2. Place macros in a dedicated file separately
When the number of macros increases, or when the same macro needs to be reused in multiple template files, it is recommended to store the macro definition in a separate file. According to the template conventions of Anqi CMS, such code snippets are usually placed in the root directory of the template.partial/In the catalog.
Step 1: Create a macro fileIn your template directory (for exampletemplate/default/), create apartial/directory and create a file within it, such as_macros.htmlAn underscore prefix is a common convention indicating that this is an auxiliary file.
Inpartial/_macros.htmlDefine your macro in the file:
{# partial/_macros.html 内容 #}
{% macro article_card(article) %}
<div class="article-item">
<h3 class="article-title"><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
{% if article.Description %}
<p class="article-description">{{ article.Description }}</p>
{% endif %}
<span class="article-date">{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
</div>
{% endmacro %}
{% macro product_thumbnail(product) %}
<div class="product-thumb">
<a href="{{ product.Link }}">
<img src="{{ product.Thumb }}" alt="{{ product.Title }}" loading="lazy">
<p class="product-name">{{ product.Title }}</p>
</a>
</div>
{% endmacro %}
Step 2: Introduce and use the macro in other templates.In your main template file (for exampleindex.htmlordetail.htmlUse it in{% import %}tags to include macro files. You can include multiple macros at once, or you can specify aliases for macros.
{# index.html 内容 #}
{% import "partial/_macros.html" article_card, product_thumbnail as thumb_macro %}
{# ... 页面其他内容 ... #}
<h2>最新文章</h2>
<div class="articles-list">
{% archiveList latestArticles with type="list" moduleId=1 limit="3" %}
{% for item in latestArticles %}
{{ article_card(item) }} {# 调用 article_card 宏 #}
{% endfor %}
{% endarchiveList %}
</div>
<h2>推荐产品</h2>
<div class="products-grid">
{% archiveList featuredProducts with type="list" moduleId=2 limit="4" %}
{% for item in featuredProducts %}
{{ thumb_macro(item) }} {# 调用 product_thumbnail 宏的别名 thumb_macro #}
{% endfor %}
{% endarchiveList %}
</div>
By{% import "partial/_macros.html" article_card, product_thumbnail as thumb_macro %}we included_macros.htmlfiles defined inarticle_cardandproduct_thumbnailTwo macros. One of them,product_thumbnailis assignedthumb_macroan alias for convenience in the current template.
The scope of the macro: withincludethe key difference.
It should be especially noted that macros and{% include %}tags have essential differences in variable scope.
{% include %}: will inherit and can directly access all variables in the parent template it calls.{% macro %}It has its own independent scope.OnlyIt can access variables passed in explicitly through parameters. This means that if you have a variable in the parent template,global_settingA variable that is not passed as a parameter to the macro cannot be accessed directly within the macroglobal_setting.
This design makes macros more independent and modular, reduces unexpected variable conflicts, and also makes the reusability of macros stronger, because it does not depend on a specific external environment.
**Practice
- Explicit naming: The name of the macro should clearly express its function or the component rendered.
- Single Responsibility: A macro should ideally be responsible for rendering a specific component or code snippet, avoiding overly complex functionality.
- Parameterization: Pass all possible variable elements through parameters to make the macro more flexible.
- Store agreements: Place all macro files in
partial/the directory for easy management and search. - Use aliases wiselyIn
importSet concise aliases for long macro names to improve readability.
By proficiently mastering the creation and application of macros, you will be able to carry out Anqi CMS template development more efficiently and elegantly, constructing high-quality websites with clear structure and easy maintenance.
Frequently Asked Questions (FAQ)
1. Can the macro access all variables on the current page?Cannot. Macros have their own scope and can only access variables explicitly passed as arguments.You must explicitly pass a variable from the parent template as a parameter to the macro if you need to use it in a macro.
2. Macro andincludeWhat is the essential difference between tags? How should I choose?The main difference lies in the scope of variables and usage scenarios:
*