How to define and call the `macro` macro function in the AnQiCMS template to create reusable code snippets?

Calendar 👁️ 59

Secure CMS template tool:macroMacro function, making code snippets accessible

During website operations and development, we always encounter scenarios where we need to repeatedly write similar code snippets, such as unified article card styles, product information display modules, or form elements with specific interactions.If each time you start from scratch, it is not only inefficient, but also makes maintenance a nightmare.AnQi CMS is well-versed in this, its powerful template engine provides us with the “macroThis macro function is a powerful tool designed to help developers and operators easily create reusable code snippets, greatly improving the development efficiency and maintenance quality of templates.

As an experienced website operations expert, I fully understand the importance of a highly efficient and customizable CMS system for content operations.AnQiCMS with its concise and efficient architecture and full utilization of the high performance of the Go language, provides us with an excellent creative platform.Today, let's delve deeply into the AnQiCMS templatemacroThe definition and invocation of the macro function, as well as how to use it to build modular, easy-to-maintain website templates.

IntroductionmacroMacro function - definition and basic application

macroA macro function, as the name implies, is like a mini function that can be defined in a template, receive parameters, and then output a preset code structure based on these parameters.It resolved the issue of code repetition in the template, making our template more DRY (Don’t Repeat Yourself).

Define one in the AnQiCMS templatemacroThe macro function is very intuitive, it uses a syntax similar to the Django template engine tags, by{% macro ... %}and{% endmacro %}Wrap. Inside the tag, we need to specify the name of the macro function and the parameters it will accept.These parameters are like function signatures, defining the information required by the macro function when it is called.

For example, we may need a unified style to display each item in the article list, including the title and link. We can define it like thisarticle_itemMacros:

{% macro article_item(article) %}
<li class="article-list-item">
    <a href="{{ article.Link }}" class="article-link">
        <h5 class="article-title">{{ article.Title }}</h5>
    </a>
</li>
{% endmacro %}

In this example,article_itemis the name of a macro function,articleIt accepts a parameter, we expect this parameter to be an object containing article (archive) data structures. The code inside the macro function defines how toarticlethe object'sLinkandTitleProperties to render a list item.

After defining the macro function, calling it is also simple. We just need to use the double curly bracket syntax where we need to use this code snippet.{{ macro_name(arguments) }}Pass the parameters. Assuming we have aarchiveslist of articles, we can call it like thisarticle_itema macro function to iterate and render:

<ul class="articles-container">
{% for item in archives %}
    {{ article_item(item) }}
{% endfor %}
</ul>

here,itemIsarchivesEach article object in the list, which is passed as a parameter toarticle_itemthe macro function. The macro function generates the correspondingitemHTML list item based on the data passed in.

It is worth noting that,macroThe macro function has an independent "scope". This means it can only access variables passed in through parameters and cannot directly access global template variables defined outside the macro function.This feature ensures the encapsulation and predictability of macro functions, making them truly reusable, side-effect-free code snippets.

macroThe organization of macro functions and efficient import

As the complexity of the website template increases, the number of macro functions may also increase.In order to better manage these reusable code snippets and keep the template file tidy, AnQiCMS allows us to save macro functions to independent files.This is like organizing functions into different modules or libraries in programming.

We can create a dedicated file, such as namedarchive.helperAnd all macro functions related to the article should be placed in this file. For example, in addition to the ones mentioned above,article_itemwe may also have onearticle_summarymacro function.

archive.helperFile content example:

{% macro article_item(article) %}
<li class="article-list-item">
    <a href="{{ article.Link }}" class="article-link">
        <h5 class="article-title">{{ article.Title }}</h5>
    </a>
</li>
{% endmacro %}

{% macro article_summary(article) %}
<div class="article-summary-card">
    <h4><a href="{{ article.Link }}">{{ article.Title }}</a></h4>
    <p>{{ article.Description|truncatechars:100 }}</p> {# 使用过滤器截断描述 #}
    <span>发布日期: {{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
</div>
{% endmacro %}

We need to use tags to import these macro functions in the main template file,{% import ... %}and we use them.importThe tag is very flexible, it can import a single macro function, multiple macro functions, and even set aliases for imported macro functions to avoid naming conflicts or simplify calls:

{% import "partial/archive.helper" article_item, article_summary as summary_card %}

<ul class="articles-grid">
{% for article in latest_articles %}
    {{ article_item(article) }} {# 调用原名的宏函数 #}
{% endfor %}
</ul>

<div class="featured-articles">
{% for featured in featured_articles %}
    {{ summary_card(featured) }} {# 调用别名为 summary_card 的宏函数 #}
{% endfor %}
</div>

In this example, we start frompartial/archive.helperimported a filearticle_itemmacro function, and use it directly. At the same time, wearticle_summaryimported the macro function and assignedsummary_cardthis alias, and then used it in subsequent codesummary_cardCall it. This organization and import method makes the template structure clear and easy to maintain, especially in large-scale website projects, its advantages will be more obvious.

macroThe application scenarios and advantages of macro functions in AnQiCMS template development

macroThe macro function plays a key role in AnQiCMS template development in enhancing efficiency and quality.Considering AnQiCMS is designed for small and medium-sized enterprises, self-media, and multi-site management, the unified content display and rapid iteration capability are its core value.

  1. Standardized content module: Whether it is an article list, product display, user comments, or sidebar navigation, many elements have similar structures. BymacroThese general modules can create standardized templates, such as a universal "card" macro function that can receive parameters such as title, image, link, description, etc., and then render uniformly.
  2. Reduce duplicate code:Imagine a website with ten or so pages that all need to display the latest article list, if notmacro, you may need to copy and paste the same HTML structure on every page. And withmacro, just define it once and call it anywhere, greatly reducing redundancy.
  3. Enhance maintainability:When the design requirements or UI style changes, for example, if the font color of all article list items needs to be adjusted, if usedmacroWe only need to modify the macro function definition once, and all the places that call it will be updated automatically, avoiding the麻烦 and potential omission of modifying each page one by one.This is especially important for operations personnel when adjusting content strategy or brand image.
  4. Simplify the template structure and improve readability:By encapsulating complex HTML fragments intomacroIn, the main template file will become more concise and clear, only retaining the overall layout and macro function calls, making the template code easier to read and understand.
  5. Supports multilingual and customization:Combine AnQiCMS multilingual support, we can flexibly handle different language text or links in macro functions, or call different resources based on specific site ID to achieve highly customized content display.

Compare and choose:macrovsinclude

In addition to the AnQiCMS template,macrowe also often useincludetags. They can all achieve code reuse, but their application scenarios are slightly different.

  • includeTagemphasizesInserting static code block directlyandInheritance of context variables. When you have a fixed HTML structure such as a header (header), footer (footer), or sidebar (aside), and you want it to access all variables of the current page, includeit is the ideal choice. For example:{% include "partial/header.html" %}.includeThe template defaults to inheriting all variables from the current template, you can also pass extra variables throughwithkeywords, oronlylimit only the specified variables to be passed.

  • macroMacro functionthen focuses more onParameterized, dynamic code logic snippet. It has its own scope and only handles data passed through parameters.When your code snippet needs to generate different outputs based on different input data, and you want this generation process to be controllable and reusable, function behavior when, macroMacro functions are a better choice.

In short, when your code snippet is 'what is', and needs to access all contextual information, chooseinclude; When your code snippet is 'how to do', and needs to be dynamically generated based on specific input, selectmacro. In actual development, both are often used together, for example, in aincludeIn the sidebar file coming in, multiple calls may be mademacroMacros are used to render different types of promotional modules.

Summary

macroMacros function as a core feature of the AnQiCMS template engine, providing powerful tools for website operators and developers to create highly reusable, easy-to-maintain template code snippets.It encapsulates parameterized code logic, which not only can greatly improve development efficiency and reduce redundancy, but also shows excellent flexibility and maintainability during the long-term operation of the website.ProficientmacroThe definition, calling, and import techniques will make your AnQiCMS content management work twice as efficient, easily mastering diverse content display needs.


Frequently Asked Questions (FAQ)

1.macroCan the macro function access the global variables of the current template?

No.macroMacros have their own scope and can only access variables explicitly passed to them as arguments.This design is to ensure the encapsulation and predictability of macro functions, so that they can produce the same results when called anywhere without being affected by the external environment.If you need data that is not in the parameter list of the macro function to be processed, you need to pass this data as a parameter.

2. Will there be an error if my macro function file does not exist?

Yes, if using{% import "file_path" ... %}Labeling the import of a non-existent file, the AnQiCMS template engine will throw an error, causing the page rendering to fail. To avoid this situation, if you are unsure whether the macro function file exists or want to silently fail (i.e., do not import the macro function but also do not report an error), you canimportAdd after tagif_existsModifiers, for example:{% import "partial/my_macros.html" my_macro if_exists %}.

3.macromacro functions andincludeWhat is the main difference between labels? When should we choose to use them?

The main difference lies in the way they handle data and the scope.

  • includeLabels tend towardsDirect insertionA static or semi-static code block defaultsInheritanceThe context of all variables in the current template. It is suitable for inserting headers, footers, sidebars, and other relatively fixed page components, or for accessing code snippets that need to access all the data on the current page.
  • macroA macro function is more like aFunction with parametersIt creates a reusable code logic snippet and can only access throughParameters passed inThe data has an independent scope. It is suitable for those that need to dynamically generate content based on different input data, such as unified article cards, product list items, or form elements, by rendering them with different data objects.

In short, when you need to "include" a segment of HTML code (which may or may not require current context data), useinclude; when you need to "generate" a segment of HTML code

Related articles

How to implement template inheritance with the `extends` tag and overwrite specific blocks of the parent template?

As an experienced website operations expert, I deeply understand that a flexible and efficient template system is crucial for the long-term development of a website.In AnQiCMS (AnQiCMS), it draws on the powerful capabilities of the Django template engine, allowing you to manage the website interface in a simple and logical way.Today, we will focus on one of the core features - the `extends` tag, and delve into how it implements template inheritance, allowing us to accurately rewrite specific blocks of the parent template.

2025-11-06

How to implement code reuse and pass additional variables using the `include` tag in template development?

As an experienced website operations expert, I am well aware of the importance of template development efficiency and code maintainability for a website in my daily work.AnQiCMS (AnQiCMS) relies on its efficient architecture based on the Go language and the Django-style template engine, providing us with powerful content management capabilities.Today, let's delve deeply into a tool that can significantly improve efficiency and code reuse in Anqi CMS template development, namely the `include` tag, especially how it helps us achieve code reuse and flexibly pass additional variables.

2025-11-06

How to use `with` or `set` tags to define and assign variables in AnQiCMS templates?

AnQiCMS's template system is known for its flexibility and ease of use, providing strong support for content operators and developers.In the presentation of content, we often need to define temporary variables to handle data, optimize logic, or pass parameters.AnQiCMS template engine borrowed the syntax style of Django templates and provided two very practical tags to help us achieve this goal: `with` and `set`.Understanding their respective features and application scenarios can make your template code clearer and more efficient.

2025-11-06

The `for` loop tag can iterate over arrays, but it also supports advanced usages like `reversed` or `empty`?

## The `for` loop in Anqi CMS template: Not just iteration, but advanced techniques to help you achieve twice the content operation results As a senior website operation expert, I am well aware of the importance of an efficient and flexible content management system for enterprises.AnQiCMS (AnQiCMS) leverages its high-performance architecture based on the Go language and Django template engine syntax to provide strong support for our content creation and display.In daily operations, we often need to present data collections in the form of lists on websites, at which time, the `for` loop traversal tag is undoubtedly our reliable helper

2025-11-06

How to output system information configured in the AnQiCMS template, such as website name, Logo, and filing number?

In the flexible world of AnQiCMS, elegantly presenting the system-level information configured in the background to the front end of the website is a core skill that every website operator and template developer needs to master.As an experienced website operations expert, I know that these seemingly trivial details are invaluable for enhancing brand image, optimizing user experience, and meeting regulatory requirements (such as displaying the filing number).Today, let's delve deeply into how to output these valuable background information in the AnQiCMS template in a natural and smooth manner. AnQiCMS

2025-11-06

What is the core function of the `archiveParams` tag in AnQiCMS template?

In the world of AnQi CMS templates, efficiently and flexibly displaying content is the key to the success of website operation.We know that a good content management system not only needs to manage standardized information but also needs to adapt to the ever-changing business needs and provide personalized content display.Today, let's delve deeply into a crucial tag in the AnQiCMS template, `archiveParams`, which is the幕后 hero behind highly customized content.What is the core function of the `archiveParams` tag in AnQiCMS templates?

2025-11-06

How to use the `archiveParams` tag to display all custom parameters of the current document in AnQiCMS template?

AnQiCMS template's `archiveParams` tag: easily display all custom parameters of the document As a senior website operations expert, I am well aware that in a content management system, how to flexibly display and utilize the various properties of documents is crucial for website customization and functional expansion. AnQiCMS, as an efficient and customizable content management system, provides a rich and powerful set of template tags, among which the `archiveParams` tag is the core tool to unlock the powerful features of document custom parameters.

2025-11-06

How is the `archiveParams` tag's `id` parameter used to retrieve custom fields of a specific document?

As an experienced website operation expert, I am happy to give you a detailed explanation of how the `archiveParams` tag's `id` parameter is used to obtain custom fields of specific documents in AnQi CMS.The AnQi CMS, with its flexible content model and powerful template tag system, provides great convenience for content operations.Grasp the essence of these tags, which can make your website content display more personalized and greatly increase operational efficiency.

2025-11-06