Security CMS Template Tool:macroMacro function makes code snippets easily accessible
During the operation and development of the website, we will 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 you start from scratch every time, it is not only inefficient, but also makes maintenance a nightmare.macroThis is a powerful macro function designed to help developers and operators easily create reusable code snippets, greatly improving the development efficiency and maintenance quality of templates.
As a senior website operations expert, I know the importance of an efficient and customizable CMS system for content operations.AnQiCMS provides an excellent creative platform for us with its concise and efficient architecture and full utilization of the high performance of the Go language.macroThe definition and usage of macro functions, as well as how to use it to build modular, easy-to-maintain website templates.
IntroductionmacroMacro function - definition and basic usage
macroMacros, as the name implies, are like mini-functions that can be defined in templates, receive parameters, and then output predefined code structures based on these parameters.It solves the problem of code repetition in templates, making our templates more DRY (Don’t Repeat Yourself).
Define a macro function in AnQiCMS templatemacroThe macro function is very intuitive, it uses tag syntax similar to Django template engine,{% macro ... %}and{% endmacro %}Packing.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 what information the macro function needs when 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_itemMacro function:
{% 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 the macro function,articleIt is the parameter it accepts, and we expect this parameter to be an object containing article (archive) data structures. The code inside the macro function defines how toarticleObjects'LinkandTitleProperty to render a list item.
After defining the macro function, calling it is also simple. Wherever this code snippet needs to be used, we just use the double-brace syntax{{ macro_name(arguments) }}and pass the corresponding parameters. Suppose we have aarchiveslist of article data, we can call it like thisarticle_itemmacro function to iterate and render:
<ul class="articles-container">
{% for item in archives %}
{{ article_item(item) }}
{% endfor %}
</ul>
Here,itemYesarchivesEvery article object in the list, it is passed as a parameter toarticle_itemthe macro function. The macro function generates the corresponding HTML list item based on theiteminput data.
It is worth noting that,macroMacros have their own "scope".This means it can only access variables passed in as 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 and side-effect-free code snippets.
macroThe organization of macro functions and efficient import
With the complexity of the website template increasing, the number of macro functions may also increase.To better manage these reusable code snippets and keep the template files neat, 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, for example namedarchive.helper,and put all macro functions related to the article in this file. For example, in addition to the ones mentioned above,article_itemwe might also have anotherarticle_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 the tag to import these macro functions in the main template file.{% import ... %}The tag to import them.importTags are very flexible, they can import a single macro function, multiple macro functions, or 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.helperfile importsarticle_itemmacro functions, and use them directly. At the same time, we willarticle_summaryimport the macro functions and assignsummary_cardthis alias, and then use it in subsequent code.summary_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 enhancing efficiency and quality in AnQiCMS template development.Considering AnQiCMS is designed for small and medium-sized enterprises, self-media, and multi-site management, the core value lies in the uniformity of content display and the ability for rapid iteration.
- Standardized content module:Whether it is an article list, product display, user comments, or sidebar navigation, many elements have a similar structure. Through
macroThese general modules can have standardized templates created, such as a universal "card" macro function that can accept title, image, link, description, and other parameters, and then render them uniformly. - Reduce duplicate code:Imagine a website with ten or so pages that all need to display the latest article list, without
macro, you might need to copy and paste the same HTML structure on each page. But withmacroJust define once, call anywhere, greatly reduces 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 it uses
macroWe only need to modify the macro function definition once, and all the calls to it will be automatically updated, avoiding the麻烦 and potential omissions of modifying each page individually.This is particularly important for operations personnel when adjusting content strategy or brand image. - Simplify template structure and improve readability:Through encapsulating complex HTML fragments to
macroauto, 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. - Support multi-language and customization:Combine with AnQiCMS multilingual support, we can flexibly handle different language texts or links in macro functions, or call different resources based on specific site ID to achieve highly customized content display.
Comparison and selection:macrovsinclude
In AnQiCMS templates, besidesmacro, we will also often useincludetags. They can all achieve code reuse, but the application scenarios are slightly different.
includetagsMore focused onStatic code block direct insertionandInheritance of context variables。When you have a header, footer, or sidebar such as this fixed HTML structure, and you want it to access all variables of the current page,includeIt is an ideal choice. For example:{% include "partial/header.html" %}.includeThe template introduced by default will inherit all variables of the current template, and you can alsowithpass additional variables through keywords, oronlyThe keyword limit only passes specified variables.macroMacro functionIt is more focused onParameterized, dynamic code logic fragments.It has a separate scope and only handles data passed through parameters.macroMacro functions are a better choice.
In short, when your code snippet is 'what is', and needs to access all context information, chooseincludeWhen your code snippet is 'how to do', and needs to generate dynamically based on specific input, choosemacro. In actual development, both are often used together, for example, in aincludeThe sidebar file being accessed may call multiplemacromacro functions to render different types of promotional modules.
Summary
macroThe macro function is a core feature of AnQiCMS template engine, providing powerful tools for website operators and developers to create highly reusable and easy-to-maintain template code snippets.It encapsulates parameterized code logic, not only significantly enhancing development efficiency and reducing redundancy, but also demonstrating excellent flexibility and maintainability in the long-term operation of the website.macroThe definition, calling, and import techniques will make your AnQiCMS content management work twice as efficient, and easily handle diverse content display needs.
Common Questions (FAQ)
1.macroCan the macro function access the global variables of the current template?
No.macroThe macro function has its own scope and can only access variables that are explicitly passed to it as arguments.This design is to ensure the encapsulation and predictability of the macro function, so that it can produce the same result in any place called, without being affected by the external environment.If the data you need to process with the macro function is not in its parameter list, you need to pass this data as an argument.
2. If my macro function file does not exist, will the import cause an error?
Yes, if using{% import "file_path" ... %}Label importing a non-existent file will cause AnQiCMS template engine to throw an error, resulting in the failure of page rendering. To avoid this, if you are unsure whether the macro function file exists or you want to silently fail (i.e., not import the macro function but also not report an error) when the file does not exist,importLabel added afterif_existsModifier, for example:{% import "partial/my_macros.html" my_macro if_exists %}.
3.macroThe macro function andincludeWhat is the main difference between tags? When should they be used?
The main difference lies in how they handle data and scope.
includeTags tend toDirect insertionStatic or semi-static code block, and defaultInheritanceThe context of all variables in the current template.It is suitable for inserting headers, footers, sidebars, and other relatively fixed parts of a page, or for code snippets that need to access all the data on the current page.macroMacro functions are more like aFunction with parameters, it creates a reusable code logic snippet and can only access throughParameters PassedThe data, has an independent scope.It is suitable for those code blocks 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 "embed" a segment of HTML code (which may or may not require current context data), useincludeWhen you need to 'generate' a segment of HTML code