As an experienced website operations expert, I know that modularization and reusability of templates are crucial when building and maintaining a website.AnQiCMS (AnQiCMS) takes advantage of its powerful Django template engine syntax, providing us with great flexibility, allowing us to easily divide pages into manageable small pieces, which are also known as sub-templates.includeWhen introducing sub-templates, a common problem 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 deeply into the strategies and methods for achieving this refined variable passing in the AnQi CMS.

The Beauty of Modularity:includeThe Foundation of Tags

In the template system of Anqi CMS,includeThe tag is undoubtedly the core of code reuse. It allows us to abstract out UI components such as headers, footers, sidebars, or any reusable UI components into independent.htmlFile, then use it at the required location through simple{% include "partial/header.html" %}statements for introduction. This greatly enhances the maintainability and development efficiency of the template.

However,includeThe default behavior of the label is: it automatically passes all available variables in the current parent template to the included sub-template.At first glance, this seems convenient, but as the scale of the project expands, a parent template may have dozens or 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, reducing the readability and maintainability of the code, but may also have a slight impact on the rendering performance of the page in extreme cases.It also blurs the responsibility boundaries of sub-templates, making them less 'independent'.

Precise delivery:withthe appearance of keywords

In order to solve the problem of this "big pot of rice" with variables, AnQi CMS providesincludeTags providewithkeywords.withAllow you to specify the specific variables to pass to the sub-template when including sub-templates.

Its usage is very intuitive: you canincludeuse after the statement, usingwiththe keyword, then define the variable you want to pass in the form ofkey="value". For example, if your sub-templatepartial/header.htmlonly needs onetitleVariables and akeywordsVariables, you can introduce them like this:

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

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

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

The benefits of doing this are that you provide a clear 'interface' to the child template: it knows which data it will receive. However, there is an important detail to note:Using onlywithKeywords will not prevent other variables in the parent template from being passed to the child template.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 “increase” or “overlay” variables, not “isolate”.

Complete isolation:onlyThe magic of the keyword

If you want a child template to have a truly "pure" execution environment, it should only receive those variables that you explicitly passwithand completely shield all other variables from the parent template.onlyThe keyword is your best choice.

onlyThe keyword is usually withwithCombined with the keyword, it tells the template engine to onlywithThe specified variable is passed to the sub-template, any other variable from the parent template will be ignored.

For example, if you wantpartial/header.htmlThe sub-template only receivestitleandkeywordsThese two variables, and they 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, attempting to access any other variables from the parent template will fail (usually manifested as variables being empty or throwing an error).

Considerations in practice and **practice

  • When to usewith(without)only)When the child template you introduce needs to access most of the parent template's context, but also requires some variables specific to this introduction (such as a special title or a dynamic CSS class),withExtremely useful. It provides the ability to customize locally while maintaining global context.

  • When to usewith ... only: When you need to build highly reusable and independent components,onlyis**a choice. For example, a list item in an article might only need apartial/article_item.html) and may 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, not affected by other complex business logic variables of the parent page. This makes the debugging and reuse of components extremely simple.

  • Enhance clarity and avoid naming conflictsNo matter which way you choose, explicitly passing variables can greatly enhance the clarity of template code.The child template no longer needs to guess which data it can obtain; its 'input' is now clear at a glance.At the same time, this can also effectively avoid conflicts that may arise in large projects when different developers may inadvertently use the same variable name in both parent and child templates.

  • Withmacrocomparison:In the Auto CMS,macroIt is also a powerful tool for code reuse, similar to functions in programming languages, accepting clear parameters.macroIt is inherently isolated with variables, and its internal access is only to the parameters passed to it. For those 'functional' template fragments that require passing multiple parameters and executing complex logic,macro可能是比include ... only更优的选择。然而,include在引入静态HTML片段或简单动态组件时,通常更轻量、直接。

By using flexibilityincludeTagswithandonlyKeywords, we can achieve fine-grained control over template variable passing in the Anqi CMS, which not only helps to write clearer and more maintainable code, but is also an indispensable part of building efficient and robust websites.


Common Questions (FAQ)

  1. Question: If I use{% include "partial/sidebar.html" only %}English, but did not passwithPass any variable, can the child template still get the variable?Answer: In this case, the child templatepartial/sidebar.htmlWill not be able to access any variables from the parent template.onlyThe purpose of the keyword is to completely cut off the child template's access to the parent template's context, unless you explicitly specify throughwithPass variables. If the child template does not define its own variables, it will execute in an 'empty' variable environment.

  2. Question: When usingwith ... onlyIf, when the parent template has a variable with the same name, for example,titleWill it be inherited by the child template?Answer: No.onlykeyword ensures that the child template can only accesswithExplicitly declared variables. Even if there is a variable namedtitlein the parent template,includethe statement is{% include "partial/header.html" with my_title="页面标题" only %}, the one accessible in the child template will bemy_title, and not able to access the parent template'stitleThe variable strengthens the independence of sub-templates.

  3. Question: BesidesincludeWhat are the ways to achieve the reuse and variable isolation of template content in, AnQi CMS?Answer: In addition toincludebeyond that, the Anqi CMS also providesmacroLabel.macroIt is more similar to a function in programming languages, which allows you to define template code blocks with explicit parameters. Invocationmacroyou need to explicitly pass parameters,macroInternally, it 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 multiple dynamic contents with the same structure but different data, providing moreinclude ... only stronger parameterization capabilities.