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 use
with(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 use
with ... 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.
with
macrocomparisonIn 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)
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.Question: When using
with ... 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.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.