In the development of website content management system templates, 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 have to copy and paste this code manually every time, it is not only inefficient but also, once you need to make modifications, you have to repeat the labor in multiple places, which is very prone to errors.

AnQiCMS (AnQiCMS) is an efficient content management system with a template engine that supports powerful syntax similar to Django, one very practical feature being the "macro function" (macro)。Macros can help us effectively reuse these commonly used content display code snippets, making 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 can accept parameters and render different content based on these parameters.In a template, defining macro functions is primarily to encapsulate those frequently occurring, structurally similar code snippets, avoid redundancy, and improve the efficiency and consistency of template development and content display.

How to define a simple macro function?

Use to define a macro function in AnQi CMS template{% macro ... %}and{% endmacro %}A label pair. A macro function needs a name, as well as a list of accepted parameters (comma-separated,Separate). 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, which accepts a parameter namedarticle_obj. Inside the macro function, we use AnqiCMS built-in template variables and filters such asarticle_obj.Link/article_obj.Title/truncatecharsandstampToDateShow the article object passed inarticle_objIts properties

Call the macro function in the template

After defining the macro function, it can be used anywhere in the template just like a regular function. The macro function is called using double curly braces.{{ ... }}Wrap it and pass the corresponding parameters.

Suppose we have a list of articles.archiveswe canarchiveListTag 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 %}

By this means,render_article_itemThe macro function will be called each time the loop runs, passing a different oneitem(i.e.),article_obj),thus rendering a list item with consistent structure but different content. This way, if we need to adjust the HTML structure or style of the list item, we only need to modifyrender_article_itemA macro function can be defined once, and all calls to it will be updated accordingly.

Organize macro functions into independent files for reuse.

As the website functionality increases, you may create multiple macro functions, and even need to share these macro functions in different template files (such as the homepage, category page, search page, etc.).At this point, defining all macro functions in the same template file will become cumbersome and difficult to manage.

The AnQiCMS template engine allows us to store macro functions in a separate file and import them as needed. Usually, we would place them in a subdirectory under the template directory, such aspartial/macrosIn it, create a macro file, such asarticle_macros.htmlorhelpers.html.

Suppose we created a file namedmacros.html, and defined the above in itrender_article_itemMacro functions, and some auxiliary macros as well. In the template files that 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 %}

By{% import "partial/macros.html" as my_macros %}, we willmacros.htmlimport all macro functions in the file, and proceed bymy_macrosThis alias to access them. Ifmacros.htmlAre defined multiple macros, such asrender_product_cardWe can go through{{ my_macros.render_product_card(product_obj) }}To call. In addition, if you only want to import specific macros, or want to give the imported macros different aliases,importLabels also support 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

Developing templates with macro functions not only makes your code cleaner, but also brings real practical convenience:

  • High code reuseAbstracts general code into macros, avoiding a lot of copy and paste, and reducing the size of template files.
  • Improve maintenance efficiencyWhen the display logic or style changes, it is only necessary to modify the macro function definition once, and all calls will take effect automatically, greatly reducing maintenance costs and the probability of errors.
  • 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: Once commonly used components are encapsulated as macros, subsequent development can be directly invoked without rewriting, thereby speeding up the development of the website.

In summary, the macro function of Anqi CMS is an invaluable tool in template development.Make good use of macro functions, which can help you build efficient, neat, and easy-to-maintain website templates, so that you can focus more on content operations themselves.


Frequently Asked Questions (FAQ)

Q1: Macro function (macro) orincludeWhat are the differences between tags?

A1:includeThe tag is used to insert the content of another template file at the current position, it is more like a simple file merge operation. TheincludeThe template can access all variables of the current template file. On the other hand, macro functions are more like independent functions in a programming language, with their own scope, and can only access variables passed as parameters. This makes them very suitable for encapsulating code snippets that require specific inputs to generate specific outputs.In short,includeSuitable for inserting a universal layout block that is static or shared across all contexts (such as header, footer), andmacroIt is suitable for encapsulating components that can 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: AnqiCMS template engine macro functions do 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). But you can make conditional judgments within the macro function ({% if ... %}To simulate default parameter values. For example, you can check whether a parameter has been passed or is empty in a macro function, and if it is empty, use a predefined default value.

Q3: If the macro file contains other ordinary HTML or template code in addition to macro functions, will this code be imported?

A3: No. When you use{% import ... %}When a macro file is imported by the tag, the template engine will only parse and import all the macro functions defined in the file.Any other regular HTML content or template logic code of non-macro functions in the macro file will be ignored and will not be imported into the current template.This ensures that the macro file can focus on defining macro functions while maintaining the purity of its content.