How to define macro functions in templates to reuse commonly used content display code snippets?

Calendar 👁️ 61

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.

Related articles

How can you reference and overwrite the base master template (extends) in a template to unify the display style?

In the world of AnQiCMS, building a website with a unified appearance, easy to manage, and efficient to update is a common pursuit of each content operator and developer.Imagine if each page of the website needed to be designed individually for the header, footer, and sidebar, then the amount of work required to modify the logo, navigation menu, or copyright information would be enormous.Luckyly, AnQiCMS cleverly utilizes the template inheritance mechanism, allowing us to easily achieve a unified display style while maintaining flexible content updates

2025-11-09

How to prevent HTML tags from being automatically escaped when content is displayed?

When using Anqi CMS to manage website content, you may encounter a seemingly small but annoying problem: the formatted HTML code entered in the background editor is displayed as plain text on the front page, even presented directly in the form of angle brackets, losing the original style and layout.This not only affects the appearance of the page, but also discounts the carefully arranged content.Why is that, and how should we solve it?###

2025-11-09

How to implement the automatic display of content collected on the website front end?

How to automatically display the collected content on the website front-end is a concern for many content operators.AnQiCMS (AnQiCMS) is an efficient and flexible content management system that provides a complete solution from content entry to front-end display.It goes through a powerful content model, flexible template tags, and a friendly SEO mechanism, making this process simple and efficient.Next, we will explore how to use the various functions of AnQiCMS to automatically and beautifully display the valuable content you collect on the website's front-end.###

2025-11-09

How to add special styles to specific items when displaying in a list, based on the count in a for loop?

In website content display, we often need to highlight specific items in the list visually, whether it is to attract the attention of users or to enhance the hierarchy of the content.For example, you may want to add a "pin" mark to the latest few articles published, or make the odd and even rows of the list display different background colors to enhance readability.AnQiCMS (AnQiCMS) flexible template engine, which provides powerful support for these refined controls.AnQiCMS's template system borrows the syntax of the Django template engine

2025-11-09

How to customize new parameters in the AnQiCMS backend settings and display them in the front-end template?

In Anqi CMS, to meet the personalized and flexible content display needs of the website, you can easily customize new parameters and call these parameters to display in the front-end template.This greatly enhances the website's customization capabilities, whether it is to display specific contact information, additional attributes of articles, or special configuration of single pages, it can do so with ease. AnQi CMS provides two main ways of custom parameters: **global parameters at the system/contacts level** and **custom fields at the content model level**. Understand these two methods and their applicable scenarios

2025-11-09

How to implement unified content management and front-end display for AnQiCMS?

In the digital age, many enterprises and content operations teams need to manage multiple websites, which may involve different brands, product lines, regions, or multilingual content.The traditional approach often means deploying multiple independent CMS systems, leading to high maintenance costs, repeated content updates, and difficult data integration.How to achieve unified management of content across multiple sites and efficient front-end display in the face of such challenges has become an urgent problem to be solved.AnQiCMS (AnQi Content Management System) is precisely in this context, providing users with a simple and powerful solution. AnQiCMS

2025-11-09

How can you customize the display layout of different types of content using a flexible content model?

In website operation, we often encounter such a need: different types of content require different display methods.The layout of a news article may be very different from that of a product detail page, and a team member introduction page may have its own unique style.The flexible content model of AnQiCMS (AnQiCMS) is designed to address this pain point, allowing us to deeply customize the structure of the content and the final display layout, thereby providing a ** browsing experience for visitors.### Understanding the Core Value of Content Modeling One of the Core Advantages of AnQi CMS

2025-11-09

How does the AnQiCMS website support the switching of multilingual content and accurate display?

Today, with the deepening of globalization, the international promotion of website content has become an important topic for many enterprises and operators.How can different language users smoothly browse your website and obtain the necessary information, which is the key to improving user experience and expanding the global market.AnQiCMS, as an efficient and flexible content management system, provides a powerful and practical multilingual solution in this regard. ### AnQiCMS's Multilingual Ability: Opening the Door to the Global Market One of the core strengths of AnQiCMS is its comprehensive "multilingual support" feature.This means

2025-11-09