As an experienced AnQiCMS (AnQiCMS) website operations manager, I know that efficiency and consistency are crucial in daily content management.Especially in the template design and content publishing stage, if code can be effectively reused, it can not only greatly improve work efficiency, but also ensure the consistency of the website's visual and functional aspects.Today, I will discuss with everyone how to create and use reusable code snippets, also known as macro functions, which are one of the key tools for our efficient operation.
Code reuse in templates: the cornerstone of improving operational efficiency
When managing and optimizing website content, we often encounter the need to reuse code blocks.These code blocks may be responsible for displaying specific types of content (such as article lists, product cards), or may be a complex UI component (such as a navigation with multi-level menus).If written from scratch each time, it not only takes time and effort, but is also prone to errors, leading to inconsistent website style.AnQiCMS's powerful template engine provides various code reuse mechanisms, among which the macro function (Macro) is an extremely flexible and efficient way, allowing us to define code snippets with parameters, achieving the true 'write once, use anywhere'.
AnQiCMS's template engine syntax is similar to Django, operators familiar with this syntax will find that the variable definition ({{变量}}) and tags ({% 标签 %})are very intuitive. Under this framework, macro functions provide us with a powerful ability to encapsulate specific logic and display formats, making template files cleaner and logic clearer.
Understand and build macro functions
A macro function, in short, is a "mini function" within a template.It allows us to encapsulate a commonly used template code and define input parameters for it.When we need to use this code at different positions in the template, we just need to call the macro function and pass in the corresponding parameters.This is very similar to the concept of functions in traditional programming languages, with its core value lying in the realization of code modularity and high reusability.
Basic syntax for creating macro functions
To define macro functions in AnQiCMS templates, you need to use{% macro 宏函数名(参数1, 参数2, ...) %}and{% endmacro %}Label pairs. For example, we may need a uniform way to display the brief information of each article:
{% macro article_card(article) %}
<div class="article-card">
<a href="{{ article.Link }}">
<img src="{{ article.Thumb }}" alt="{{ article.Title }}" class="article-thumbnail">
<h3 class="article-title">{{ article.Title }}</h3>
<p class="article-description">{{ article.Description|truncatechars:100 }}</p>
<span class="article-meta">{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
</a>
</div>
{% endmacro %}
In this example,article_cardIs the name of a macro function that accepts a name calledarticleThe parameter. The code inside the macro function utilizes thisarticleParameters to display its title, thumbnail, description, and publication time information.It is worth noting that macro functions can only use variables passed through parameters, which ensures the independence of their scope and avoids unnecessary variable conflicts.
Invoke the macro function
After defining the macro function, it is very simple to call it. Suppose we have aarchivesList, needs to be displayed in a uniform card format:
{% for item in archives %}
{{ article_card(item) }}
{% endfor %}
Thus,archivesover each element in the listitemwill be passed as parameters toarticle_cardmacro function, then rendered in the format we preset.
module management and import of macro function
To maintain the neatness of the template file and the maintainability of macro functions, we usually define the macro functions in independent auxiliary files rather than write them directly in the main template. For example, we can create a file named_macros.htmlThe file (usually placed in/template/your_template_name/partial/directory, or in a certain code snippet directory under the root template directory).
Example of independent file storage (_macros.html)
{# _macros.html 文件内容 #}
{% macro article_card(article) %}
<div class="article-card">
<a href="{{ article.Link }}">
<img src="{{ article.Thumb }}" alt="{{ article.Title }}" class="article-thumbnail">
<h3 class="article-title">{{ article.Title }}</h3>
<p class="article-description">{{ article.Description|truncatechars:100 }}</p>
<span class="article-meta">{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
</a>
</div>
{% endmacro %}
{% macro product_listing(product) %}
<div class="product-item">
<img src="{{ product.Logo }}" alt="{{ product.Title }}">
<h4>{{ product.Title }}</h4>
<p>价格: {{ product.Price }}</p>
</div>
{% endmacro %}
Importing and using macro functions
In the main template file (for exampleindex.htmlorlist.htmlIn it, you can use{% import %}label to import them:
{# index.html 或其他主模板文件内容 #}
{% import "partial/_macros.html" as common_macros %}
{# 现在可以使用导入的宏函数了 #}
<h2>最新文章</h2>
{% archiveList latest_articles with type="list" limit="5" %}
{% for article in latest_articles %}
{{ common_macros.article_card(article) }}
{% endfor %}
{% endarchiveList %}
<h2>推荐产品</h2>
{% archiveList featured_products with type="list" moduleId=2 limit="3" %}
{% for product in featured_products %}
{{ common_macros.product_listing(product) }}
{% endfor %}
{% endarchiveList %}
Byas common_macros, we will_macros.htmlimport the macro functions defined in it and assign them aliases. This way, we can go throughcommon_macros.article_cardandcommon_macros.product_listingCall them clearly indicating the source of these macro functions. If the file contains only one macro function, or you do not want to use aliases, you can also import directly:{% import "partial/_macros.html" macro_name %}.
The reasonable choice of macro function, Include and Extends
In AnQiCMS template,include/extendsAnd the macro function are powerful tools for code reuse, but they have their own focuses:
extends(Template Inheritance)It is used to define the skeleton of the page layout. For example,base.htmlIt can define the common structures such as the header, footer, sidebar of the page, and other pages inherit it and useextendsit.blockLabeling or filling specific area content. This is applicable to the structural reuse of the entire page.include(Code snippet included)Used to insert static HTML fragments that do not require parameterized logic. For example, a fixed footer content, a navigation bar area that does not change, can be inserted directlyincludeCome in. It simply copies the file content to the current position and inherits all variables of the current template.- Macro Function (Macro)Used to handle dynamic, the same structured code block that needs to be rendered according to different data.When you find that a UI component or content display mode needs to be reused in multiple places, and the data passed in each use is different, then a macro function is**the choice.**It provides stricter scope and parameter control, making the code more robust and predictable.
Application scenarios of macro functions in actual operation
In daily website operation and content optimization, the application scenarios of macro functions are very extensive:
- Standardized content display componentsFor example, a "news list item", "product display card", "user comment area", etc., by defining the structure and style of the macro function, content can be displayed uniformly at any place on the website, whether it is the homepage recommendation, category list, or search results page.
- Dynamic generation of a complex navigation menuWhen the navigation menu needs to be dynamically generated based on user permissions or content hierarchy, macro functions can encapsulate recursive logic to render multi-level menu items in a consistent format.
- Unified processing of SEO optimization elementsAlthough AnQiCMS provides TDK tags, for some specific metadata or structured data (such as JSON-LD), macro functions can help us encapsulate the logic for dynamically generating these data, ensuring that each page can generate segments in line with SEO standards as needed.
- Advertising space or feature moduleIf a website needs to display the same structure but different content of advertisements or feature modules in multiple locations, macro functions can help us efficiently manage these areas and quickly adjust their display logic.
By creating and utilizing macro functions, we can build highly modular and easy-to-maintain AnQiCMS templates.This not only greatly improves the efficiency of template development, but also provides a solid foundation for the long-term operation and iteration of the website's content, ensuring the consistency and high quality of the displayed content.
Frequently Asked Questions (FAQ)
1. Macro functions withincludeWhat are the main differences between tags?
The main difference between macro functions is that they support parameter passing and have their own scope.includeThe label is more like a simple file content 'copy and paste', it will inherit all variables of the current template.And macro functions are more like functions in programming languages, they only handle data passed through parameters, which makes macro functions more flexible, controllable, and better at encapsulating specific logic.When a code block needs to render based on different input data, it is advisable to use macro functions first.
2. Can I use other AnQiCMS built-in tags or filters in macro functions?
Of course you can. The code inside the macro function is the same as the normal template code, you can freely use all the built-in tags provided by AnQiCMS (such as{% archiveList %}/{% categoryDetail %}), filters (such as|truncatechars/|date) and other macro functions. This allows macro functions to build very complex dynamic content fragments without losing the powerful features of the AnQiCMS template engine.
How to handle HTML content escaping in macro functions, especially when the parameters contain HTML tags?
The AnQiCMS template engine defaults to escaping output content to prevent XSS attacks. If the macro function's parameters contain HTML tags and you want these tags to be parsed correctly by the browser instead of being displayed as plain text, you need to use the variable when outputting the parameter|safeFilter. For example, ifarticle.Descriptionit may contain HTML, it should be written as{{ article.Description|safe }}. Please make sure to use the filter only when you are sure that the content source is safe and reliable|safeto avoid potential security risks.