In the template development of a website content management system, we often encounter situations where we need to repeatedly write the same or similar code snippets to display specific types of content.For example, each article card in the blog article list, each product feature item on the product detail page, although their content is different, their structure and style are highly similar.If you copy and paste these codes manually every time, it is not only inefficient but also, once a modification is needed, it has to be repeated in multiple places, which is prone to errors.
AnQiCMS as an efficient content management system, its template engine supports powerful syntax similar to Django, and one very practical feature is the "macro function" (macroThe macro function can help us effectively reuse these commonly used content display code snippets, making the template code more concise, readable, and maintainable.
What is the template macro function?
We can understand template macro functions as functions in programming languages.It is a predefined, reusable code block that accepts parameters and renders different content based on these parameters.Define macro functions in the template, the core purpose of which is to encapsulate those frequently occurring, structurally similar code snippets, avoid redundancy, and improve the efficiency and consistency of content display in template development.
How to define a simple macro function?
Define macro functions in the AnQi CMS template using{% macro ... %}and{% endmacro %}Label pair. A macro function requires a name, as well as a list of acceptable parameters (parameters separated by commas),分隔). For example, we may need a unified style to display the title and link of each article on the website. We can define a macro function like this:
{% macro render_article_item(article_obj) %}
<li class="article-item">
<a href="{{ article_obj.Link }}" title="{{ article_obj.Title }}">
<h3 class="article-title">{{ article_obj.Title }}</h3>
<p class="article-description">{{ article_obj.Description|truncatechars:100 }}</p>
<span class="article-date">{{ stampToDate(article_obj.CreatedTime, "2006-01-02") }}</span>
</a>
</li>
{% endmacro %}
In this example,render_article_itemis the macro function name we define, it accepts a parameter namedarticle_obj. Within the macro function, we use built-in template variables and filters of AnqiCMS (such asarticle_obj.Link/article_obj.Title/truncatecharsandstampToDate) to display the article object passed inarticle_obj. Its properties.
Call macro functions in the template
After defining a macro function, you can use it anywhere in the template just like a regular function. A macro function is called using double curly braces{{ ... }}and pass the corresponding parameters.
Assume we have a list of articlesarchiveswe can directly get its value througharchiveListLabel retrieval:)
{% archiveList archives with type="list" limit="5" %}
<ul class="article-list">
{% for item in archives %}
{{ render_article_item(item) }} {# 调用宏函数,传入当前循环的文章对象 #}
{% empty %}
<p>目前没有文章发布。</p>
{% endfor %}
</ul>
{% endarchiveList %}
In this way,render_article_itemThe macro function will be called every time through the loop, passing a different one each timeitem(i.e.,)article_objThus rendering a list of article items with consistent structure but different content. In this way, if we need to adjust the HTML structure or style of the article list items, we only need to modifyrender_article_itemThe macro function can be placed in one place, and all the calls to it will be updated accordingly.
Organize the macro function into an independent file for reuse.
With the addition of website features, you may need to create multiple macro functions, and even share these macro functions across different template files (such as the homepage, category page, search page, etc.).It would be cumbersome and difficult to manage if all macro functions are defined in the same template file.
The AnQi CMS template engine allows us to store macro functions in a separate file and import them as needed. Typically, we would place them in a subdirectory under the template directory (such aspartial/macrosCreate a macro file in the)article_macros.htmlorhelpers.html.
Assuming we have created a file named)macros.htmland defined the above in itrender_article_itemMacros, and some other auxiliary macros. In the template files where we need to use these macros, we can use{% import ... %}tags to import them:
{# 在某个模板文件(如 index.html 或 list.html)的顶部 #}
{% import "partial/macros.html" as my_macros %}
{# ... 其他模板代码 ... #}
{% archiveList archives with type="list" limit="5" %}
<ul class="article-list">
{% for item in archives %}
{{ my_macros.render_article_item(item) }} {# 通过别名调用宏函数 #}
{% empty %}
<p>目前没有文章发布。</p>
{% endfor %}
</ul>
{% endarchiveList %}
Pass{% import "partial/macros.html" as my_macros %}, we willmacros.htmlAll macro functions imported in the file, and throughmy_macrosthis alias to access them. Ifmacros.htmlmultiple macros are defined inrender_product_card, we can access them through{{ my_macros.render_product_card(product_obj) }}Call it. In addition, if you only want to import specific macros or want to assign different aliases to the imported macros,importThe tag also supports more flexible syntax:
{# 导入单个宏并直接使用 #}
{% import "partial/macros.html" render_article_item %}
{# 导入多个宏并分别起别名 #}
{% import "partial/macros.html" render_article_item as article_macro, render_product_card as product_macro %}
Significant advantages brought by macro functions
Use macro functions for template development, not only makes your code cleaner, but also brings real convenience:
- High code reusabilityAbstracting general code into macros avoids a lot of copy-paste, reducing the size of template files.
- Enhance maintenance efficiencyWhen the logic or style changes, only the macro function definition needs to be modified once, and all the calling places will take effect automatically, greatly reducing the maintenance cost and error probability.
- Enhance template readabilityThrough macro functions, complex logic is encapsulated, making the main template file clearer and allowing one to see the page structure at a glance, rather than being overwhelmed by lengthy HTML code.
- Accelerate the development process[en]Once a component is encapsulated as a macro, it can be directly called during subsequent development without the need to rewrite, thereby speeding up the development of the website.
In summary, the macro functions of Anqi CMS are a rare tool in template development.Effectively utilizing macro functions can help you build efficient, neat, and easy-to-maintain website templates, allowing you to focus more on content operation itself.
Common Questions (FAQ)
[en]Q1: Macro function (macro) andincludeWhat is the difference between tags?
A1:includeThe role of a tag is to directly insert the content of another template file at the current position, which is more like a simple file merge operation.includeThe template can access all variables of the current template file.While macro functions are more like independent functions within a programming language, they have their own scope and can only access variables passed in as parameters. This makes them particularly well-suited for encapsulating code snippets that require specific inputs to generate specific outputs.includeApplicable for inserting universal layout blocks that apply to all contexts (such as headers and footers), andmacroThis is applicable for encapsulating components that accept parameters and generate different content based on the parameters (such as article cards, product detail lines).
Q2: Can macro functions define default parameter values?
A2: The macro function of AnqiCMS template engine does not support setting default values directly in the parameter list as some programming languages do (for example{% macro my_macro(param1, param2="default_value") %}This syntax). However, you can use conditional judgments within the macro function ({% if ... %}[en] To simulate default parameter values. For example, you can check whether a parameter has been passed or is empty within a macro function, and if it is empty, use a predefined default value.
Q3: If the macro file contains other plain HTML or template code in addition to the macro functions, will this code be imported?
A3: No. When you use{% import ... %}When importing a macro file with the tag, the template engine will only parse and import all the macro functions defined in the file.Any other ordinary HTML content in the macro file or template logic code that is not a macro function will be ignored and will not be imported into the current template.This ensures that the macro file can focus on the definition of macro functions, maintaining the purity of its content.