How to pass specific variables or data when including a sub-template?

Advanced Template: Anqi CMSincludePassing Data Techniques and Practices of Subtemplates

In the template development of Anqi CMS,includeTags are undoubtedly a powerful tool for enhancing the reusability and modularization of templates.It allows us to extract common code snippets (such as page headers, footers, sidebars, etc.) and then introduce them where needed, thus avoiding repetition and making the template structure clearer and maintenance more efficient.However, the sub-templates introduced often need to display different content, which raises a core issue: how to pass specific variables or data when introducing sub-templates?

Why Do You Need to PassincludeData in Subtemplates?

Imagine the navigation bar or card components in the article list of a website.These components' HTML structure may be consistent throughout the entire website, but the titles, links, images, or summaries they need to display are dynamically changing.If the sub-template can only use global variables or variables of the current page itself, its reusability will be greatly reduced, and it may even be necessary to write almost identical sub-templates for each page.

In order for the child template to flexibly adapt to different usage scenarios, we need a mechanism that can "feed" some specific data to it when it is introduced, so that it can render itself based on this data.The Auto CMS provides a very intuitive and powerful way to do this.

in AQ CMSincludeBasic usage of tags

First, let's take a look back atincludeThe Basic Form of Tags. If you have a name ofpartial/header.htmlThe public header file, you can include it in any master template like this:

{# 主模板文件 (例如:index.html) #}
{% include "partial/header.html" %}

If you worry that the included file may not exist and cause page errors, you can addif_exists:

{% include "partial/header.html" if_exists %}

So, ifheader.htmlExists, it will be introduced; if it does not exist, it will be ignored without throwing an error.

Core function: throughwithKeyword to pass specific variables

English CMS template engine (based on Django style with GoLang) allows you to usewithKeywords are passed to the child template to introduce additional variables. These variables are only available in the child template and its internalincludeAvailable in the chain, it will not pollute the parent template or the scope of other unrelated templates.

1. Pass a single variable:

If you only want to pass a specific variable, you can do it like this:

{# 主模板文件 (例如:index.html) #}
{% include "partial/page_title.html" with title="安企CMS官网首页" %}

Inpartial/page_title.htmlThis sub-template, you can directly use thistitleVariable:

{# 子模板文件 (例如:partial/page_title.html) #}
<h1>{{ title }}</h1>

2. Pass multiple variables:

When multiple variables need to be passed,withThe keyword should be listed after a colon, separated by spaces in key-value pair format:

{# 主模板文件 (例如:index.html) #}
{% include "partial/meta_tags.html" with pageTitle="安企CMS官网首页" keywords="安企CMS,建站,内容管理" description="安企CMS是一个高效、可定制的企业级内容管理系统。" %}

Inpartial/meta_tags.htmlThese variables can be accessed directly in the sub-template:

{# 子模板文件 (例如:partial/meta_tags.html) #}
<title>{{ pageTitle }}</title>
<meta name="keywords" content="{{ keywords }}">
<meta name="description" content="{{ description }}">

3. Limit the scope of variables:onlyKeyword

By default, throughincludeThe sub-template introduced can not only accesswithPassed variable, can access all variables defined in the parent template (global variables and current context variables). But in some scenarios, you may want the child template to only receivewithPassing variables without inheriting other variables from the parent template, in order to maintain the independence and predictability of the child template. At this time, you can useonlyKeyword:

{# 主模板文件 (例如:index.html) #}
{% include "partial/card.html" with item=productData only %}

This is,partial/card.htmlThe child template can only accessitemThis variable, while inaccessibleindex.htmlMay exist in addition to the variables mentioned. This helps avoid potential name conflicts and makes it easier for child templates to understand and reuse.

Comprehensive Example

Let us demonstrate how to pass data between parent and child templates with a more comprehensive example. Suppose we have a child template used to display article cardspartial/article_card.htmland a main template containing a list of articleslist.html.

partial/article_card.html(Sub-template):

<div class="article-card">
    <a href="{{ article.Link }}" title="{{ article.Title }}">
        <img src="{{ article.Thumb }}" alt="{{ article.Title }}" class="card-img">
        <h3 class="card-title">{{ article.Title }}</h3>
    </a>
    <p class="card-description">{{ article.Description }}</p>
    <div class="card-meta">
        <span>发布日期:{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
        <span>浏览量:{{ article.Views }}</span>
    </div>
    {% if showEditButton %}
        <button class="edit-btn">编辑文章</button>
    {% endif %}
</div>

list.html(Main template):

{# 假设 archives 变量是从后台获取的文章列表数据 #}
{% archiveList archives with type="page" limit="10" %}
    <div class="article-list">
        {% for item in archives %}
            {# 引入文章卡片子模板,并传递当前文章数据和是否显示编辑按钮的标志 #}
            {% include "partial/article_card.html" with article=item showEditButton=true %}
        {% endfor %}
    </div>

    {# 分页标签 #}
    {% pagination pages with show="5" %}
        {# ... 分页代码 ... #}
    {% endpagination %}
{% endarchiveList %}

In this example,list.htmlPassforLoop through the article dataarchivesIn each iteration, it goes throughincludeLabel Introductionpartial/article_card.htmlSub-template, and throughwithPassed two variables with the keyword:

  • article: Represents the current loop article object.
  • showEditButton: A boolean value that controls whether the 'Edit Article' button is displayed in the sub-template.

This is,article_card.htmlcan be rendered based on thearticlethe detailed information of the object, and according toshowEditButtonthe value to determine whether to display specific UI elements, greatly enhancing the flexibility and reusability of the template.

Actual application scenarios and **practice

  • General UI Component:Navigation menu, breadcrumbs, comment form, product thumbnail cards, user avatar/information display, and more. These components usually only need a small amount of dynamic data to render.
  • Layout blocks: Sidebar content, specific ad slots, notification messages, etc., the content may vary according to the page or user status.
  • Avoid redundant logic:Wrap the general judgment, formatting logic in subtemplates, and trigger these logic by passing simple data.
  • Clear variable naming:InwithWhen passing variables, use clear and meaningful names so that developers of sub-templates can immediately understand the purpose of these variables.
  • Use Appropriatelyonly:When the child template does not need to access the full context of the parent template, useonlyCan help you better isolate the scope, reduce coupling, making the child template more like an independent, portable component.

By masteringincludeLabel and data passing techniques, you will be able to build more modular, maintainable, and scalable security CMS website templates.


Common Questions (FAQ)

  1. Q: Why can't I access the variable in the child template even though I passed it?A: Please check the following points:

    • Variable name spelling and case sensitivity:The variables in the AnQi CMS template are case-sensitive, please make sure that the variable names used in the sub-template match.withThe variable names passed are exactly the same.
    • onlyKeyword usage:If you are inincludeThe label used containsonlykeywords, then the sub-template will only receivewiththe variables explicitly passed later. Please check if you have missed any variable that needs to be passed, or if you have misusedonly.
    • the variable type:Ensure that the data type (such as string, number, object) you pass is used correctly in the sub-template.
  2. Q:includeHow is the path to the template file parsed?A:includeThe template file path in the tag is relative to the root directory of the currently active template (usually `/template/