How to create reusable code snippets (macro functions) in templates?

Calendar 👁️ 63

As an experienced AnQiCMS (AnQiCMS) website operations manager, I know that efficiency and consistency are crucial in daily content management.Especially in the template design and content publishing stage, if code can be effectively reused, it can not only greatly improve work efficiency, but also ensure the consistency of the website's visual and functional aspects.Today, I will discuss with everyone how to create and use reusable code snippets, also known as macro functions, which are one of the key tools for our efficient operation.

Code reuse in templates: the cornerstone of 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 may be a complex UI component (such as a navigation with multi-level menus).If written from scratch each time, it not only takes time and effort, but is also prone to errors, leading to inconsistent website style.AnQiCMS's powerful template engine provides various code reuse mechanisms, among which the macro function (Macro) is an extremely flexible and efficient way, allowing us to define code snippets with parameters, achieving the true 'write once, use anywhere'.

AnQiCMS's template engine syntax is similar to Django, operators familiar with this syntax will find that the variable definition ({{变量}}) and tags ({% 标签 %})are very intuitive. Under this framework, macro functions provide us with a powerful ability to encapsulate specific logic and display formats, making template files cleaner and logic clearer.

Understand and build macro functions

A 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 in the corresponding parameters.This is very similar to the concept of functions in traditional programming languages, with its core value lying in the realization of code modularity and high reusability.

Basic syntax for creating macro functions

To define macro functions in AnQiCMS templates, you need to use{% macro 宏函数名(参数1, 参数2, ...) %}and{% endmacro %}Label pairs. For example, we may need a uniform 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 that accepts a name calledarticleThe parameter. The code inside the macro function utilizes thisarticleParameters to display its title, thumbnail, description, and publication time information.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.

Invoke the macro function

After defining the macro function, it is very simple to call it. Suppose we have aarchivesList, needs to be displayed in a uniform card format:

{% for item in archives %}
    {{ article_card(item) }}
{% endfor %}

Thus,archivesover each element in the listitemwill be passed as parameters toarticle_cardmacro function, then rendered in the format we preset.

module management and import of macro function

To maintain the neatness of the template file and the maintainability of macro functions, we usually define the macro functions in independent auxiliary files rather than write 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 certain code snippet directory under the root template directory).

Example of independent file storage (_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 file (for exampleindex.htmlorlist.htmlIn it, you can use{% import %}label 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 %}

Byas common_macros, we will_macros.htmlimport the macro functions defined in it and assign them aliases. This way, we can go throughcommon_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 %}.

The reasonable choice of macro function, Include and Extends

In AnQiCMS template,include/extendsAnd the macro function are powerful tools for code reuse, but they have their own focuses:

  • extends(Template Inheritance)It is used to define the skeleton of the page layout. For example,base.htmlIt can define the common structures such as the header, footer, sidebar of the page, and other pages inherit it and useextendsit.blockLabeling or filling specific area content. This is applicable to the structural reuse of the entire page.
  • include(Code snippet included)Used to insert static HTML fragments that do not require parameterized logic. 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 position and inherits all variables of the current template.
  • Macro Function (Macro)Used to handle dynamic, the same structured code block that needs to be rendered according to 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 a 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 daily website operation and content optimization, the application scenarios of macro functions are very extensive:

  • Standardized content display componentsFor example, a "news list item", "product display card", "user comment area", etc., by defining the structure and style of the macro function, content can be displayed uniformly at any place on the website, whether it is the homepage recommendation, category list, or search results page.
  • Dynamic generation of a complex navigation menuWhen 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.
  • Unified processing of SEO optimization elementsAlthough 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 segments in line with SEO standards as needed.
  • Advertising space or feature moduleIf a website needs to display the same structure but different content of advertisements or feature modules in multiple locations, 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 operation and iteration of the website's content, ensuring the consistency and high quality of the displayed content.


Frequently Asked Questions (FAQ)

1. Macro functions withincludeWhat are the main differences between tags?

The main difference between macro functions is that they support parameter passing and have their own scope.includeThe label is more like a simple file content 'copy and paste', it will inherit all variables of the current template.And macro functions are more like functions in programming languages, they only handle data passed through parameters, which makes macro functions more flexible, controllable, and better at encapsulating specific logic.When a code block needs to render based on different input data, it is advisable to use macro functions first.

2. Can I use other AnQiCMS built-in tags or filters in macro functions?

Of course you can. The code inside the macro function is the same as the normal template code, you can freely use all the 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.

How to handle HTML content escaping in macro functions, especially when the parameters contain HTML tags?

The 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 parsed correctly by the browser instead of being displayed as plain text, you need to use the variable when outputting the parameter|safeFilter. For example, ifarticle.Descriptionit may contain HTML, it should be written as{{ article.Description|safe }}. Please make sure to use the filter only when you are sure that the content source is safe and reliable|safeto avoid potential security risks.

Related articles

How to unify the overall layout and structure of the website through the template inheritance mechanism?

As an experienced CMS website operation person, I know the importance of an efficient and unified template system for website operation.AnQi CMS, with its high-performance architecture based on the Go language and flexible template system, provides us with powerful tools to ensure the consistency of content display, the unity of brand image, and greatly improve the efficiency of content management and publication.The importance of unified website layout and structure Maintaining consistency in the overall layout and structure of a website is crucial for attracting and retaining users in website operations.a mess

2025-11-06

How to directly call the built-in methods of Go struct in the template?

As a professional who has been deeply engaged in the content operation of Anqi CMS for a long time, I know that the template plays a core role in the presentation of website content.A highly efficient and flexible template system that can greatly enhance the efficiency and richness of content publishing.AnQi CMS, with its powerful backend based on Go language, provides template developers with the ability to directly interact with the underlying data structure, one very practical feature being the ability to directly call built-in methods defined in Go structs in the template.

2025-11-06

How to get the list of related articles for the current article (based on category, keywords, or manual association)?

As a website operator who is deeply familiar with the operation of AnQiCMS, I know that high-quality content and user experience play a key role in the success of a website.Articles related can effectively extend the user's stay on the site, increase page views, and are also very beneficial for the internal link optimization (SEO) of the website.AnQiCMS provides a flexible way to obtain and display these related contents, meeting the operational needs of different scenarios.

2025-11-06

How to automatically convert URLs and email addresses in the text content into clickable links?

Today, with the increasing richness and frequent updates of digital content, website operators not only need to pay attention to the quality of the content, but also to the way it is presented and the user interaction experience.When we publish articles, product descriptions, or any text information on AnQiCMS (AnQiCMS), we often include some URL links and email addresses pointing to external resources or contact information.If this information is only displayed in plain text, users will have to manually copy and paste, which undoubtedly increases the complexity of the operation and reduces the user experience.

2025-11-06

How to implement batch replacement of keywords or links in website article content?

As a long-term深耕 website operator who has a deep understanding of AnQiCMS (AnQiCMS), I know that content is the lifeline of the website, and efficient content management is the key to success.In daily operations, we often encounter the need to update keywords or links in a large number of articles on the website, which may be due to brand strategy adjustments, SEO optimization needs, changes in links from external cooperative partners, or even legal and regulatory requirements.Facing thousands of articles, manually modifying one by one is undoubtedly a nightmare that consumes time and effort.It's lucky that

2025-11-06

How to get all the subcategory lists under a specific category?

As an experienced CMS website operations personnel, I fully understand that flexible management of the website classification system is crucial for content organization and user experience.Especially when your website content becomes richer and the classification structure becomes complex, the ability to accurately and efficiently obtain the list of all subcategories under a specific category is an indispensable ability for template development and content display.AnQi CMS provides a powerful and easy-to-use template tag system, making this operation very simple.Flexiblely obtain the list of all subcategories under the specific category of Anqicms

2025-11-06

How to get the detailed content and images of a single page (such as "About Us")?

Managing and displaying a single page like "About Us" and its content and images in Anqi CMS is an efficient and flexible process.As an experienced website operator, I will explain in detail how to create from the backend to the frontend display, and fully master this feature.--- **To get the detailed content and images of a single page (such as "About Us") in AnQiCMS** AnQiCMS (AnQiCMS) provides a dedicated management module called "Single Page" for independent pages such as "About Us" and "Contact Us"

2025-11-06

How to deploy AnQiCMS multi-site in Docker environment and configure reverse proxy?

As an experienced CMS website operation person, I fully understand the importance of an efficient and flexible content management system for enterprises and self-media in the increasingly complex network environment.AnQi CMS, with its high-performance architecture based on the Go language, rich feature set, and SEO-friendliness, has become the ideal choice for many users.Especially in multi-site management, AnQiCMS provides a simple and efficient solution.

2025-11-06