As an experienced AnQiCMS website operations personnel, I know that efficiency and consistency are extremely important in daily content management.Especially in template design and content publishing, being able to effectively reuse code can not only greatly improve work efficiency, but also ensure the consistency of website visuals and functionality.Today, I will discuss with everyone how to create and utilize reusable code snippets, also known as macro functions, which is one of the key tools for our efficient operation in AnQiCMS templates.
Code reuse in templates: The foundation for 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 they may be complex UI components (such as navigation with multi-level menus).If you rewrite from scratch each time, it not only takes time and effort, but is also prone to errors, leading to inconsistent website style.AnQiCMS powerful template engine provides various code reuse mechanisms, among which macro function (Macro) is a highly flexible and efficient way, allowing us to define code snippets with parameters and achieve the true 'write once, use anywhere'.
AnQiCMS的模板引擎语法类似于Django,熟悉这种语法的运营人员会发现其变量定义({{变量}})和标签({% 标签 %})are very intuitive. Under this framework, macro functions provide us with a powerful ability to encapsulate specific logic and display formats, making template files more organized and logic clearer.
Understand and construct macro functions
The 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 the corresponding parameters.This is very similar to the concept of functions in traditional programming languages, with the core value of achieving modularization and high reusability of code.
Basic syntax for creating macro functions
To define macro functions in the AnQiCMS template, you need to use{% macro 宏函数名(参数1, 参数2, ...) %}and{% endmacro %}Label pair. For example, we may need a unified 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, which accepts a parameter namedarticleThe parameter. The code inside the macro function uses thisarticleThe parameter is used to display its title, thumbnail, description, and publication time.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.
Call the macro function
After defining the macro function, calling it is very simple. Suppose we have aarchivesList, needs to be displayed in a uniform card form.
{% for item in archives %}
{{ article_card(item) }}
{% endfor %}
This is,archivesin the listitemWill be passed as a parameter toarticle_cardThe macro function, then rendered in the format we预设.
Module management and import of macro function
To maintain the cleanliness of the template file and the maintainability of macro functions, we usually define macro functions in separate auxiliary files instead of writing 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 code snippet directory under the root template directory).
Independent file storage example (_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 files that need to use these macro functions (such asindex.htmlorlist.html), you can use{% import %}tags 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 %}
Passas common_macros, we will_macros.htmldefined in the macro function import and given an alias. This way, we can access it viacommon_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 %}.
Macros function, reasonable selection of Include and Extends
In AnQiCMS templates,include/extendsAnd macros functions are powerful tools for code reuse, but they have their own focuses:
extends(Template Inheritance):Used to define the skeleton of the page layout. For example,base.htmlyou can define the general structures such as header, footer, sidebar of the page, and other pages inherit it and useextendsit.blockLabel covers or fills the content of a specific area. This is suitable for structural reuse throughout the entire page.include(Code snippet included)English for inserting static, non-parametrized HTML fragments. 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 location and inherits all variables of the current template.- Macro Function (Macro):Used to handle dynamic, code blocks that need to render the same structure based on 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 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 the daily operation and content optimization of websites, the application scenarios of macro functions are very extensive:
- Standardized content display componentsFor example, a 'news list item', 'product display card', 'user comment section', etc., defined by macro functions in terms of their structure and style, can be displayed uniformly at any place on the website, whether it is the homepage recommendation, category list, or search results page.
- Complex navigation menu dynamic generationWhen 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.
- SEO optimization elements unified processing:Although 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 SEO-compliant fragments as needed.
- Advertising space or special moduleIf the website has multiple locations that need to display the same structure but different content for advertisements or featured modules, 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 content operation and iteration of the website, ensuring the consistency and high quality of the website content display.
Common Questions (FAQ)
1. Macro functions andincludeWhat are the main differences between tags?
The main difference between macro functions is that they support parameter passing and have their own scope.include标签更像是一个简单的文件内容“复制粘贴”,它会继承当前模板的所有变量。The macro function is more like a function in a programming language, it only processes the data passed in through parameters, which makes the macro function more flexible, controllable, and better at encapsulating specific logic.When the code block needs to render based on different input data, it is preferable to use macro functions.
2. Can I use other AnQiCMS built-in tags or filters in macro functions?
Of course. The code inside the macro function is the same as ordinary template code, and you can freely use all 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.
3. How to handle the HTML escaping of content in macro functions, especially when the parameters contain HTML tags?
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 correctly parsed by the browser instead of being displayed as plain text, you need to use|safeFilter. For example, ifarticle.Descriptionit may contain HTML, it should be written as{{ article.Description|safe }}. Please make sure the content source is safe and reliable before using|safethe filter to avoid potential security risks.