How to define and call the `macro` macro function in the AnQiCMS template to create reusable code snippets?
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.
- Standardized content module: Whether it is an article list, product display, user comments, or sidebar navigation, many elements have similar structures. By
macroThese 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. - Reduce duplicate code:Imagine a website with ten or so pages that all need to display the latest article list, if not
macro, 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. - 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 used
macroWe 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. - Simplify the template structure and improve readability:By encapsulating complex HTML fragments into
macroIn, 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. - 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