What are the core differences between the `macro` tag and the `include` tag in terms of variable scope and code reuse?

As an experienced website operations expert, I have a deep understanding of the powerful functions and content operation strategies of AnQiCMS (AnQi CMS).The Anqi CMS, with its efficient architecture based on the Go language, flexible content model, and SEO-friendly support, has become the preferred tool for many small and medium-sized enterprises and content operation teams.macroTags andincludeLabels are two powerful tools to achieve this goal.

However, many developers who are new to the Aanqi CMS template often feel confused about the usage scenarios of these two tags, especially the core differences in variable scope and code reuse methods.Today, let's delve into the unique features of these 'twin brothers'.

includeLabels: 'Legos' for template assembly.

Imagine that your website has many pages, which all share some common elements, such as the header, footer, or sidebar.This part of the code is often fixed and unchanged, or differs only in a few places.includeLabels are like pre-assembled Lego bricks that allow you to directly insert these independent function modules into any template file you need.

Its core idea is 'direct embedding': when you use{% include "partial/header.html" %}the system willheader.htmlThis file's content is loaded unchanged into the corresponding position of the current template. This method is concise and efficient, especially suitable for static code blocks that are relatively stable and not subject to frequent changes.

In variable scope,includeThe tag has a very important feature:By default, it will inherit all available variables in the current template.This means that any data you define in the main template can be directly accessed in the child templates. For example, if your main template definesincludethe website name variable, then{{ siteName }}this variable will be used for the website name.header.htmlEven if there is no explicit reception, it can be used directly{{ siteName }}Show.

Of course, if you want toincludeYou can use it to pass additional, module-specific variables to the templatewithKeyword. For example, if you want to display a special title in the header of a page you are linking to, you can write it like this:{% include "partial/header.html" with pageTitle="安企CMS官网" %}. At this point,header.htmlInternally it can be through{{ pageTitle }}to get this value.

Further, if you are worried aboutincludethe template unexpectedly accessing the main template's variables you don't want it to know, or to maintain the purity of the code, you can also addonlyKeyword:{% include "partial/header.html" with pageTitle="安企CMS官网" only %}This is how it goes,header.htmlonly access to the onewithspecified explicitlypageTitleVariable, any other main template variables will be invisible. It's like setting an independent power supply for the LEGO bricks, so only its own light bulb lights up.

macro标签:flexible and customizable “function factory”

Withincludeis different from the direct embedding of “macroLabels are more like a 'template function' or 'code factory'.It allows you to define a reusable code snippet with parameters, which can then be "generated" into different HTML content by passing in different data as needed.This is particularly powerful when it is necessary to display different data in the same structure, such as each product card in a product list, each article summary in an article list.

macroThe key to the tag is itsstrict variable scope isolation.”macrowithin macro definitions,Only variables accessed through explicit parameters can be accessed. It does not automatically inherit any variables from the parent template, even if you define them in the main templatesiteName,macroThe internal cannot be used directly. This "sandbox" mechanism ismacrothe most distinctive feature of the label, and it is the cornerstone for achieving high modularity and avoiding variable conflicts.

For example, suppose you need to display an article list on multiple pages, with each list item having the same layout and style, but different content. In this case, you can define amacroProcess the rendering of a single article item:

{# 定义在单独的文件如:archive.helper中 #}
{% macro article_card(item) %}
<li class="article-item">
    <a href="{{ item.Link }}">
        <img src="{{ item.Thumb }}" alt="{{ item.Title }}" class="article-thumb">
        <h5 class="article-title">{{ item.Title }}</h5>
        <p class="article-description">{{ item.Description|truncatechars:100 }}</p>
        <span class="article-date">{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
    </a>
</li>
{% endmacro %}

Then in your main template, you need to useimportto import this macro, and then use it as you would a function:

{# 在主模板中引入宏文件 #}
{% import "archive.helper" article_card %}

{# 调用 archiveList 标签获取文章数据 #}
{% archiveList archives with type="list" limit="6" %}
    <ul class="article-list">
        {% for article in archives %}
            {# 将每篇文章数据 item 传入 macro 进行渲染 #}
            {{ article_card(article) }}
        {% endfor %}
    </ul>
{% endarchiveList %}

Here,article_cardThe macro only knows what it has passeditemParameter received data, no need to carearchivesHow variables are obtained, and are not affected by any other variables in the main template. This clear division of responsibilities makes the template code easier to understand, maintain, and collaborate with the team.

Core Difference: Variable Scope and Code Reusability Philosophy

In summary,macroandincludeThe most fundamental difference lies inVariable ScopeandCode Reusability Philosophy.

  1. Variable Scope:

    • include:It shares all variables of the default parent template. It can be accessed bywithpassing additional variables throughonlylimiting to use only the passed variables. Its scope is wider, more "open".
    • macro:Strict isolation. Only variables explicitly passed as parameters can be accessed. Its scope is narrower and more 'enclosed', eliminating the possibility of variable name conflicts.
  2. Code reuse method:

    • include:Focuses on 'Structural Reusability'.It embeds a complete or partial template file into another template, suitable for the overall layout of websites, fixed blocks (such as navigation, advertisement slots), and so on.It can be regarded as a modularization of static content.
    • macro:Emphasizes 'functional reuse'.It defines a parameterizable logic fragment, like a function, that accepts data and generates HTML, suitable for components that need to render the same structure repeatedly but with different data (such as list items, cards, form fields).It can be regarded as a componentization of dynamic content.

Said simply, when you need to insert an "independent HTML file fragment" on the page, chooseincludeWhen you need to 'generate the same HTML structure with different data repeatedly' on the page, choosemacro.

Why are these differences important?

Understand and use appropriatelymacroandincludethe difference is crucial for content operators and template developers of safety CMS:

  • improve code quality and maintainability: macroThe strict scope prevents variable conflicts, reduces the risk of introducing unexpected bugs, and is particularly advantageous in large and complex templates or when working in multi-team collaborations.
  • Optimize template structure and readability:The template with clear logic is easier to understand and reduces the cost of later maintenance. UsemacroEncapsulate the repeated rendering logic to make the main template more focused on data flow and component combination.
  • Enhance the flexibility and extensibility of templates: macroCan handle data in a parameterized manner, allowing the same macro to be applied to different data sources, greatly enhancing the reusability and adaptability of the template.When you need to adjust the style or logic of a component, you only need to modify the macro definition, and all calls to the macro will be updated automatically.
  • Improve development efficiency:Avoids rewriting a large amount of similar code, generating complex content through simple parameter passing, which greatly accelerates template development speed.

The reason why AnQi CMS provides two different template reuse mechanisms is to meet different development needs and scenarios.As operation experts, we know that in efficient content management, the cleanliness, maintainability, and flexibility of code are equally important.macroandinclude,can help make your security CMS website template development more powerful, easily building professional and easy-to-manage high-quality websites.


Common Questions (FAQ)

Q1: Can I define inincludethe file internal definitionmacroThen use this in the parent template that contains this filemacro?

A1: No.macromust be defined throughimporttag is explicitly included. If you define one in a fileincludethatmacromacro is only available in theincludeFile visible internally (if it uses itself), or needs to beimportreferenced by other templates. Justincludeone file will not make itsmacrointernally defined items automatically available in the parent template.

Q2: If myincludeThe file needs a specific variable, but I don't want it to inherit all the variables from the parent template, what should I do?

A2: This is exactlywithandonlywhere keywords come into play. You can write it like this{% include "partial/my_specific_component.html" with data=my_data only %}like this,my_specific_component.htmlThe template can only accessdatathis variable, and will not inherit other variables from the parent template