In AnQi CMS, efficiently managing website content and front-end display is the key to daily operations.When faced with some repeated page elements, such as article list items, product cards, or buttons with specific styles, if we rewrite the code each time, it not only takes time and effort, but is also prone to errors, and future modifications and maintenance will become particularly complex.macroThe macro function is the tool to solve this pain point, it can help us define reusable content display segments, thereby greatly improving development efficiency and the maintainability of templates.
macroA macro function, you can imagine it as a "mini-function" or "content component" in the template.It allows you to encapsulate a piece of HTML code with specific logic and style, and define some parameters for this code.When you need to use this code, just call the macro as a function and pass in the corresponding parameters, and you can quickly generate the desired content.This way, you avoid rewriting the same template code, making the template structure clearer and easier to manage.
Define a macro function
You will use a macro function to define in the Anqi CMS template{% macro %}and{% endmacro %}This is a label. A macro function needs a name, as well as a list of parameters that can be received, which are used like ordinary variables inside the macro.
We take a common scenario as an example: In various places on the website, you may need to display a structured article summary card, including the article title, link, introduction, and thumbnail. We can define a macro like this:
{# 定义在 /template/您的模板目录/partial/_article_card.html 文件中 #}
{% macro article_card(article) %}
<div class="article-card">
<a href="{{ article.Link }}" class="article-link">
{% if article.Thumb %}
<img src="{{ article.Thumb }}" alt="{{ article.Title }}" class="article-thumb">
{% endif %}
<h3 class="article-title">{{ article.Title }}</h3>
<p class="article-description">{{ article.Description|truncatechars:100 }}</p>
<span class="article-date">{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
</a>
</div>
{% endmacro %}
In this example, we define a macro namedarticle_cardthat takes a namedarticleparameter. Inside the macro, we usearticleproperties (such asLink/Title/Thumb/Description/CreatedTime)to construct the HTML structure. Please note that we usedtruncatecharsa filter to truncate the article summary, and usestampToDateThe function formatted the publish time, all of these are powerful features provided by the Anqie CMS template engine.
Introduce and use macros in the template.
Once you define a macro, you can call it in any template file where you need to use it. Anqi CMS encourages storing such reusable code snippets inpartial/In the directory, this structure is clearer.
Assuming you have defined the abovearticle_cardmacro saved/template/您的模板目录/partial/_article_card.htmlin the file. Now, in your home page template (such asindex/index.html) or other list page template, you can useimportLabel to introduce it:
{# 在 /template/您的模板目录/index/index.html 文件中 #}
{# 引入宏文件,并给引入的宏函数指定一个别名 card #}
{% import "partial/_article_card.html" as card %}
<section class="latest-articles">
<h2>最新文章</h2>
<div class="article-list-grid">
{% archiveList articles with type="list" moduleId="1" limit="6" order="id desc" %}
{% for item in articles %}
{# 调用宏,并传入当前文章数据 #}
{{ card.article_card(item) }}
{% endfor %}
{% empty %}
<p>暂时没有文章发布。</p>
{% endarchiveList %}
</div>
</section>
<section class="recommended-articles">
<h2>推荐文章</h2>
<div class="article-list-flex">
{% archiveList recommendedArticles with type="list" moduleId="1" limit="4" flag="c" order="views desc" %}
{% for item in recommendedArticles %}
{# 在另一个区域再次调用宏,显示推荐文章 #}
{{ card.article_card(item) }}
{% endfor %}
{% empty %}
<p>暂时没有推荐文章。</p>
{% endarchiveList %}
</div>
</section>
In this example:
- We use
{% import "partial/_article_card.html" as card %}Introduced the macro file, and throughas cardGave the macro component a simpler namespace. - Following, in the loop of different article lists (latest articles and recommended articles), we all called
{{ card.article_card(item) }}. Here,itemthat isarchiveListthe data of each article looped out by the tag, which was passed as a parameter toarticle_cardmacro.
Imagine for a moment, if notmacro, you may need to change at eachforIn a loop, copy and paste the same HTML structure and data rendering logic.Once you need to modify the style or display content of an article card (such as adding a reading volume field), you will need to modify it one by one in all the places it is used, which is undoubtedly time-consuming and prone to errors.macro, you just need to modify_article_card.htmlThis file, all the places that refer to it will be synchronized for updates, greatly improving efficiency and consistency.
macroAdvantages and Application Scenarios
macroThe strength of macro functions is reflected in the following aspects:
- Reduce code redundancy:Encapsulate repeated UI components to make your template code more concise.
- Improve maintenance efficiency:Modify a macro definition, all places using it will be automatically updated, avoiding the cumbersome global search and replace.
- Enhance code readability: The macro function abstracts complex HTML structures and logic into a simple call, making template code easier to understand.
- Promote teamwork:Different developers can focus on developing different macros and then easily integrate them into the main template.
In addition to article cards,macroit can also be applied to many places, such as:
- Product list items:On e-commerce websites, product cards are composed of product thumbnails, names, prices, buy buttons, and other elements.
- Comments display:The display format of unified comment user avatar, username, comment content, and timestamp.
- Breadcrumbs navigation item:If your breadcrumbs navigation has multiple styles or complex link logic.
- Button Group:A combination of buttons with specific icons, text, and links.
- Form Input Field:Standardized input box with labels, placeholders, and validation prompts.
By flexible applicationmacroMacro function, you will be able to build and maintain your safe CMS website template more elegantly and efficiently.
Frequently Asked Questions (FAQ)
1.macromacro functions andincludeWhat are the differences between tags?
includeThe tag is used to directly insert the entire content of a template file into the current position, and it inherits all the context variables of the current template.macroThe macro function is more like an independent小程序, it only receives variables passed in as parameters, and has its own independent scope, and cannot directly access variables outside the macro definition. In simple terms,includeIs it to directly copy the code snippet?macroIs it to define a callable, parameterizable functional component?
2.macroCan macro functions access variables outside the macro?No.macroThe macro function has a limited scope and can only access variables passed through parameters.This means that if any data is needed within the macro, you must explicitly pass it as a parameter.This is to ensure the independence and reusability of the macro, to avoid its behavior being unexpectedly affected by the external environment.
3. Where should the macro file be placed in the template directory?It is strongly recommended to place the macro definition file in your template directory to maintain the clarity and standardization of the template structure.partial/In a subdirectory. For example, if your template directory isdefaultthen the macro files can be placed in/template/default/partial/_macros.htmlor further subdivided according to function, such as/template/default/partial/_article_snippets.htmlThis helps in managing and finding reusable code snippets.