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

Anqi CMS Template Advanced:includeThe technique and practice of data transmission in subtemplates

In the template development of AnQi CMS,includeThe tag is undoubtedly a powerful tool to enhance 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 more maintainable.However, these imported sub-templates often need to display different content, which raises a core issue: how can specific variables or data be passed to the sub-template when it is imported?

Why do you need to pass toincludePass data to the subtemplate?

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

In order for the sub-template to be flexible in adapting to different usage scenarios, we need a mechanism that can 'feed' it some specific data when it is introduced, so that it can render itself according to these data.AnQi CMS provides a very intuitive and powerful way to achieve this.

in Anqi CMSincludeBasic usage of tags

First, let's reviewincludeThe basic form of tags. If you have a tag namedpartial/header.htmlThe common header file, you can include it like this in any main template:

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

If you worry that the included file may not exist and cause the page to error, you can add it.if_exists:

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

so ifheader.htmlIt will be introduced if it exists; if it does not exist, it will be ignored without throwing an error.

Core feature: throughwithKeyword to pass a specific variable

The Anqicms template engine (based on GoLang with Django style) allows you to usewithKeywords pass additional variables to the included sub-template. These variables are only available within the included sub-template and its internalincludeAvailable in the chain, it will not pollute the parent template or any unrelated template scope.

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.htmlIn this sub-template, you can directly use thistitleVariable:

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

2. Pass multiple variables:

When you need to pass multiple variables, just inwithAfter the keyword, list the key-value pairs separated by spaces:

{# 主模板文件 (例如: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 included sub-template can also accesswithPassing variables, you can also access all variables defined in the parent template (global variables and current context variables). But in some cases, 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 point, you can useonlyKeyword:

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

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

Comprehensive example

Let us demonstrate with a more complete example how to pass data between a parent template and a child template. Assume we have a child template for displaying article cardspartial/article_card.htmlincluding a master 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(master 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.htmlByforLoop through 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.

Thus,article_card.htmlCan be based on the inputarticleto render the detailed information of the object and according toshowEditButtondetermine whether to display a specific UI element, greatly enhancing the flexibility and reusability of the template.

Application scenarios and **practice

  • Universal UI Component:Navigation menu, breadcrumb, comment form, product thumbnail card, user avatar/information display, and so on. These components usually need to receive a small amount of dynamic data to render.
  • Layout block:Sidebar content, specific ad spots, notification messages, etc., which may vary according to the page or user status.
  • Avoid redundant logic: Encapsulate the general judgment and formatting logic in sub-templates, triggering these logic through 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.
  • Reasonable useonly:When the child template indeed does not need to access the full context of the parent template, useonlyIt can help you better isolate the scope, reduce coupling, and make the sub-template more like an independent, portable component.

Through proficiencyincludeTags and data passing techniques, you will be able to build more modular, easy to maintain and expandable AnQi CMS website templates.


Frequently Asked Questions (FAQ)

  1. Q: Why can't I access the variable passed, even in the sub-template?A: Please check the following points:

    • Variable name spelling and case:The variables in AnQiCMS templates are case-sensitive, please make sure that the variable names used in the sub-templates match thewithvariable names passed.
    • onlyKeyword usage:If you are inincludeused in theonlyKeywords, then the sub-template will only receivewithVariables explicitly passed. Please check if you have missed some variables that need to be passed, or if you have used them incorrectlyonly.
    • 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 template file path parsed?A:includeThe template file path is relative to the root directory of the currently active template (usually `/template/')