As an experienced website operations expert, I deeply understand the importance of the neat, efficient, and maintainable template code for the long-term operation of the website. In a flexible and powerful content management system like AnQiCMS, it is important to fully utilize its template engine features, especially macro functions (macroIt can greatly enhance development efficiency and the quality of content display. Today, let's delve into how when you define multiple in different filesmacroHow to cleverly import and utilize functions.
Unlock the potential of templates: Efficiently import and use macros in Anqi CMS.
in the AnQi CMS template world,macroMacros are like a Swiss Army knife in your toolbox, allowing you to define reusable code snippets and pass parameters as if calling a function to generate dynamic content.This mechanism greatly reduces code redundancy and improves the cleanliness and maintainability of the template.
Macro functions: The concept of 'functions' in templates.
In simple terms, a macro function is a named block of template code that can accept parameters and return specific HTML or text content.You can encapsulate any UI element or data display logic that repeats into a macro.For example, a single article card in an article list, a specification display area on a product detail page, or a unified form input box, can all be implemented through macro functions.
Define a macro functionThe syntax is very intuitive:
{% macro macro_name(parameter1, parameter2, ...) %}
{# 宏函数的内容,可以使用传入的参数 #}
<div class="my-component">
<h3>{{ parameter1 }}</h3>
<p>{{ parameter2 }}</p>
</div>
{% endmacro %}
here,macro_nameThe name of the macro, inside the parentheses are the parameters it accepts.{% macro %}and{% endmacro %}Between them, you can write any template code and use the passed parameters to dynamically generate content.
Why do we need macro functions?
Imagine, your website has dozens of pages, each of which needs to display a similar product card or article summary.If there is no macro function, you may need to write almost the same HTML structure and data binding logic on each page.This takes time and once there is a minor change in design or data structure, you need to manually modify it in all related files, which is undoubtedly an operation nightmare.
The introduction of macro functions, perfectly solves these pain points:
- Code reuse:Once defined, called multiple times, avoiding redundant work.
- Maintenance convenience:Just modify the definition of the macro function, and all the places that call it will be automatically updated.
- to enhance readability:The template code becomes more concise, focusing only on the overall layout of the page, and hiding the details of complex components in macro functions.
- Team collaboration:Different developers can focus on developing different macro functions and then easily integrate them.
Organize your macro function files.
In order to maintain the neatness and structured of template code, we usually place these reusable macro definitions in the template directory or create one inside.partial/folder, or create one inside.macros/Subfolder. For example, you can create a file namedpartial/_common_macros.htmlto store the website's general macro functions, or divide according to functional modules, such aspartial/_article_macros.html/partial/_product_macros.htmletc.
This clear file organization method allows you and your team to quickly locate, understand, and manage the definition of macro functions.
Import macro function: connect different files
Once you have defined a macro function in a separate template file, the next step is to import it on the page where you need to use it. The Anqi CMS template engine providesimportTag to implement this feature.
basic import syntaxAs follows:
{% import "file_path" macro_name %}
Herefile_pathIs the file path where you define the macro function, which is usually a relative path to the current template root directory. For example, if_common_macros.htmlis locatedpartial/directory, then the path is"partial/_common_macros.html".
import multiple macro functions
If you define multiple macro functions in a macro file, you can optionally import one, several, or even all of them.
Import a single macro function:
{% import "partial/_common_macros.html" my_single_macro %}Import multiple macro functions (comma-separated):
{% import "partial/_common_macros.html" macro1, macro2, another_macro %}Set alias for macro functions (
asKeyword):When the name of the macro function you import may conflict with the variable name in the current template, or when you want to use a simpler and easier-to-remember name,askeywords come into play.{% import "partial/_common_macros.html" original_macro_name as my_alias %}You can also import multiple macros at once and set aliases:
{% import "partial/_common_macros.html" macro1, macro2 as second_macro_alias %}By alias, you can clearly distinguish macros from different sources and avoid potential naming conflicts, which is particularly important in large projects.
Use imported macro functions
After importing the macro function, use it as a regular function. Just use double curly braces.{{ }}Wrap the macro function name and its required parameters.
{# 假设您在 partial/_common_macros.html 中定义了一个名为 'render_card' 的宏 #}
{# 并传入了文章标题和摘要作为参数 #}
{{ render_card(article.Title, article.Description) }}
A comprehensive example.
Let's go through a simple scenario to tie the entire process together: we need to display the summary information card of the article uniformly on the home page and the category list page.
1. Atpartial/_article_macros.htmlDefine macros in:
{# partial/_article_macros.html #}
{% macro article_summary_card(article_obj) %}
<div class="article-card">
<a href="{{ article_obj.Link }}">
{% if article_obj.Thumb %}<img src="{{ article_obj.Thumb }}" alt="{{ article_obj.Title }}"/>{% endif %}
<h4>{{ article_obj.Title }}</h4>
</a>
<p>{{ article_obj.Description|truncatechars:100 }}</p>
<div class="meta">
<span>{{ stampToDate(article_obj.CreatedTime, "2006-01-02") }}</span>
<span>阅读量: {{ article_obj.Views }}</span>
</div>
</div>
{% endmacro %}
{% macro other_utility_macro(text) %}
<p>这是一个辅助宏: {{ text }}</p>
{% endmacro %}
2. Inindex.html(or)archive/list.htmlImport and use macro:
{# index.html 或 archive/list.html #}
{% extends "base.html" %} {# 继承基础模板 #}
{# 导入文章摘要卡片宏和另一个辅助宏 #}
{% import "partial/_article_macros.html" article_summary_card, other_utility_macro as helper_text_macro %}
{% block content %}
<div class="main-content">
<h2>最新文章</h2>
<div class="article-list">
{% archiveList latest_articles with type="list" limit="6" order="id desc" %}
{% for article in latest_articles %}
{# 调用导入的宏函数来渲染每篇文章卡片 #}
{{ article_summary_card(article) }}
{% empty %}
<p>暂无文章。</p>
{% endfor %}
{% endarchiveList %}
</div>
{# 使用别名导入的辅助宏 #}
{{ helper_text_macro("网站内容正在持续更新中!") }}
</div>
{% endblock %}
Through this example, we can clearly see that by defining macro functions in a separate file and by using them,importLabel it flexibly and use it, our template code becomes extremely tidy and efficient.
**Practical Suggestions
- Maintain the focus of the macro:Each macro function should focus on a single responsibility and avoid having too many functions in one macro function.
- Clear naming:The naming of macro functions and their parameters should be descriptive, making it easy for people to understand their purpose at a glance.
- Centralized management:Develop the habit of placing all macro function files in a specific directory (such as
partial/macros/)