How to pass specific variables to an included sub-template without sharing all variables of the parent template?

Calendar 👁️ 63

As an experienced website operations expert, I know that modularity and reusability of templates are crucial when building and maintaining a website.AnQiCMS (AnQiCMS) with its powerful Django template engine syntax provides us with great flexibility, allowing us to easily divide the page into manageable blocks, which are also called sub-templates.However, when usingincludeWhen introducing a sub-template, a common question is: how to ensure that the sub-template only receives the variables it truly needs, rather than all variables from the parent template, to avoid unnecessary 'variable pollution'?

Today, let's delve into the strategies and methods of achieving this refined variable transmission in Anqi CMS.

The beauty of modularization:includeThe foundation of tags

In the template system of Anqi CMS,includeTags are undoubtedly the core of implementing code reuse. They allow us to extract such reusable UI components as headers, footers, sidebars, or any other reusable UI components into independent.htmlFile, then at the required location through a simple{% include "partial/header.html" %}statement for introduction. This greatly enhances the maintainability and development efficiency of the template.

However,includeThe default behavior of the tag is: it automatically passes all available variables in the current parent template to the included sub-template.At first glance, this may seem convenient, but as the scale of the project expands, a parent template may have dozens even hundreds of variables, most of which are unrelated to the child template.This may not only lead to unexpected variable conflicts in sub-templates, but also reduce the readability and maintainability of the code, and even in extreme cases, it may have a slight impact on the rendering performance of the page.What is more important, it blurs the responsibility boundaries of the sub-template, making it less 'independent'.

Precise delivery:withThe appearance of keywords

To solve the problem of this 'variable big pot' problem, Anqi CMS providesincludeTags providedwithkeywords.withAllow you to specify the specific variables to be passed to the sub-template when including sub-templates.

Its usage is very intuitive: you canincludeuse after the statement,withthen use the keyword,key="value"in the form to define the variable you want to pass. For example, if your sub-templatepartial/header.htmlonly needs onetitleA variable and akeywordsA variable, you can introduce it like this:

{% include "partial/header.html" with title="这是声明给header使用的title" keywords="这是声明给header使用的keywords" %}

Inheader.htmlIn the sub-template, you can use these variables directly:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{title}}</title>
    <meta name="keywords" content="{{keywords}}">
    <!-- 其他头部内容 -->
</head>

The benefit of doing this is that you provide a clear interface for the sub-template: it knows what data it will receive. However, there is an important detail to pay attention to:Just usewithThe keyword does not prevent other variables from being passed to the child template along with it.That is to say, the child template can still access all variables in the parent template that have not beenwithExplicitly overridden.withThe function is to "add" or "override" variables, not to "isolate".

Complete isolation:onlyThe magic of the keyword

If you want a child template to have a truly 'clean' execution environment, it should only receive those variables that you explicitly passwithand completely shield all other variables from the parent template, thenonlyKeywords are your best choice.

onlyKeywords are usually withwithCombined with keywords, it tells the template engine, only towithThe specified variable is passed to the sub-template, any other variables from the parent template will be ignored.

For example, if you wantpartial/header.htmlThe sub-template only receivestitleandkeywordsThese variables, and do not touch the rest of the parent template context, you can modify it like this:

{% include "partial/header.html" with title="这是声明给header使用的title" keywords="这是声明给header使用的keywords" only %}

In this case,header.htmlIn the child template, except fortitleandkeywordsOutside of this, trying to access any other variables in the parent template will fail (usually manifested as variables being empty or causing errors).

Consideration in practice and **practice

  • When to usewith(without)only)When a child template needs to access most of the parent template's context but also needs some variables specific to this inclusion (such as a special title or a dynamic CSS class),withExtremely useful. It provides local customization while retaining the global context.

  • When to usewith ... only: When you need to build highly reusable, independent components, onlyIs **selected. For example, a list item of an articlepartial/article_item.htmlmay only need onearticleobject to render its title, summary and link. Using{% include "partial/article_item.html" with article=current_article only %}can ensure that this list item only depends onarticleVariables are not disturbed by other complex business logic variables on the parent page. This makes debugging and reuse of the component extremely simple.

  • Enhancing clarity and avoiding naming conflicts: Regardless of the way you choose, explicitly passing variables can greatly enhance the clarity of template code.The child template no longer needs to guess what data it can obtain, its "input" becomes clear.At the same time, this can also effectively avoid conflicts that may arise in large projects when different developers inadvertently use the same variable names in parent and child templates.

  • withmacrocomparisonIn AnQi CMS,macroIt is also a powerful tool for code reuse, similar to functions in programming languages, receiving clear parameters.macroIt is inherently characterized by variable isolation, and it can only access the parameters passed to it internally. For those 'functional' template fragments that require passing multiple parameters and executing complex logic,macroIt might be compared toinclude ... onlya better choice. However,includeWhen introducing static HTML snippets or simple dynamic components, they are usually lighter and more direct.

By flexible applicationincludelabel'swithandonlyKeyword, we can achieve fine-grained control of template variable transmission in Anqi CMS, which not only helps to write clearer and more maintainable code, but is also an indispensable part of building an efficient and robust website.


Frequently Asked Questions (FAQ)

  1. Ask: If I used{% include "partial/sidebar.html" only %}, but did not passwithany variables, can the child template still get the variables?Answer: In this case, the child templatepartial/sidebar.htmlUnable to obtain any variables from the parent template.onlyThe keyword's role is to completely cut off the access of the child template to the parent template context, unless you explicitlywithPass the variable. If the sub-template does not define its own variables, it will execute in an 'empty' variable environment.

  2. Question: When usingwith ... onlyIf the parent template has a variable with the same name, for example,titleDoes it get inherited by the child template?Answer: No.onlyThe keyword ensures that the child template can only accesswithExplicitly declared variables. Even if there is a variable namedtitlein the parent template, if yourincludestatement is{% include "partial/header.html" with my_title="页面标题" only %}, The one that can be accessed in the sub-template will bemy_title, and cannot directly access the parent template'stitlevariable. This strengthens the independence of the sub-template.

  3. Question: Besides,includeHow can AnQi CMS achieve template content reuse and variable isolation in other ways?Answer: Besidesincludethe following, Anqi CMS also providesmacro.macroIt is more similar to a function in programming languages, which allows you to define a template code block with explicit parameters. CallmacroWhen, you need to explicitly pass parameters,macroInternal can only access these parameters passed in, thus naturally realizing variable isolation. For example:

    {% macro my_button(text, link) %}
        <a href="{{ link }}">{{ text }}</a>
    {% endmacro %}
    
    <!-- 调用 macro -->
    {{ my_button("了解更多", "/about-us") }}
    

    macroIt is very useful when rendering dynamic content with the same structure but different data multiple times, providing stronger parameterization capabilities.include ... onlyStronger parameterization capabilities.

Related articles

How to ensure that the template file is included when using the `include` tag to avoid page errors?

As an experienced website operations expert, I fully understand how important modularization and reusability are in the construction and maintenance of websites.AnQiCMS (AnQiCMS) leverages its efficient architecture based on the Go language and Django-like template engine, providing great flexibility for content display.Among them, the `include` tag is one of the core functions for implementing template reuse.However, powerful tools also need to be used with caution, otherwise they may bring unexpected 'surprises' to the website - such as page errors caused by the non-existent template files. Today

2025-11-07

In AnQi CMS template, how to modularly reuse the common header and footer code?

In the daily operation of website management, efficiency and maintainability are one of the key factors that determine the success or failure of the project.How to efficiently manage common website elements such as header navigation, footer copyright information, etc., in content management systems (CMS), is a question that every website operations expert will ponder.AnQiCMS (AnQiCMS) provides us with an elegant solution with its flexible template engine and modular design concept.This article will delve into how to use modular strategies in the AnQiCMS template

2025-11-07

Does AnQiCMS's Tag feature provide an intelligent recommendation mechanism similar to 'Recommended Tag' or 'Related Tag'?

As an experienced website operations expert, I am well aware of the core role of tags (Tag) in content management and SEO optimization.A high-efficiency tagging system can not only help users find the content they are interested in quickly, but also improve the efficiency of search engine crawling and the overall weight of the website.AnQiCMS is a system focused on enterprise-level content management, emphasizing efficiency and scalability. The implementation of its Tag function, as well as whether it integrates an intelligent recommendation mechanism, is naturally a focus for content operators.Today, let's delve deeply into the Tag feature of AnQiCMS

2025-11-07

How does AnQiCMS handle the associated Tag of a deleted document? Will these Tags be automatically cleaned up?

As an experienced website operations expert, I know the importance of content management systems (CMS) in daily operations.AnQiCMS with its efficient and flexible features has become our excellent content management assistant.Today, let's delve deeply into a question that is often overlooked in content operation but is crucial: what happens to the Tag (label) associated with a document deleted in AnQiCMS?Will these Tags be automatically cleaned by the system?

2025-11-07

In Anqi CMS template, how can the `include` tag achieve more efficient component-based development and maintenance?

As an experienced website operations expert, I fully understand that in the current era of rapid iteration and high efficiency, the efficiency and maintainability of template development are of great importance to the success of the project.AnQiCMS (AnQiCMS) provides a solid foundation for us with its high-performance architecture based on the Go language and flexible modular design.Among many tools to improve development efficiency, the `include` tag provided by Anqi CMS template is undoubtedly a key tool for achieving more efficient modular development and maintenance.

2025-11-07

How to pass multiple parameters to the `include` tag and what is the correct syntax and separator?

As an experienced website operations expert, I am well aware that how to flexibly use the template function in a high-efficiency content management system like AnQiCMS, especially the `include` tag, is crucial for building a maintainable and easily expandable website.Today, let's delve into the correct syntax and separator when you need to pass multiple parameters to a template fragment using the `include` tag.

2025-11-07

How to quickly build a shared sidebar, navigation, or other UI components using the `include` tag?

As an experienced website operation expert, I deeply understand the importance of website efficiency and user experience, and both often cannot be separated from a set of excellent and easy-to-maintain template systems.AnQiCMS (AnQiCMS) with its concise and efficient features, provides us with powerful content management capabilities.Today, let's delve into a seemingly simple yet extremely practical feature—the `include` tag, and see how it helps us quickly build reusable, maintainable website UI components, thereby enhancing overall operational efficiency.--- ## Advanced AnQi CMS

2025-11-07

How does the `include` tag handle the optionality when the template to be included may not exist?

As an experienced website operations expert, I know that the use of templates in a highly efficient and flexible content management system like AnQiCMS is the core of website design and content presentation.It not only determines the appearance of the website, but also directly affects the presentation effect and user experience.Today, let's delve deeply into a practical and elegant little trick in template development: how does AnQiCMS's `include` tag handle this optionality when the template to be included may not exist.

2025-11-07