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

Calendar 👁️ 68

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/')

Related articles

How to use the `include` tag to reuse header, footer, and other common code segments in AnQiCMS templates?

Building website templates in AnQiCMS, efficient code reuse is the key to improving development speed and maintenance efficiency.Imagine, the header (Header) and footer (Footer) of a website appear almost on every page. If the same code is written on each page, it is not only time-consuming, but also, once a modification is needed, it has to be searched and updated on each page, which is undoubtedly a huge amount of work.

2025-11-08

How to safely output content containing HTML tags in AnQiCMS templates (e.g., article content)?

Guide to safely output HTML content in AnQiCMS templates When building a website with AnQiCMS, we often need to display content with rich formatting, such as article content, product descriptions, category details, or single-page content.This content is usually entered through the backend rich text editor, which will naturally contain HTML tags such as `<p>`, `<strong>`, `<em>`, `<a>`, and so on.How to correctly and safely output this content with HTML tags in the front-end template is a very important issue.If handled improperly

2025-11-08

How to alternate different CSS classes or styles while looping through list items?

In web design, to enhance visual aesthetics and user experience, we often encounter situations where we need to alternate different CSS classes or styles for list items (such as article lists, product lists, navigation menus, etc.).For example, make the background color of odd and even rows different, or apply a unique layout style every few items.AnQiCMS (AnQiCMS) leverages its flexible template engine to provide a variety of simple and efficient methods to meet this requirement.

2025-11-08

How to display the default prompt information when the article list obtained through `archiveList` is empty?

When using Anqi CMS to build a website, we often need to display lists of articles, products, or other content.These lists are usually dynamically retrieved and rendered using such template tags as `archiveList`.}However, if a list is empty for various reasons (such as temporarily no content under a category, or empty search results), the user experience will be greatly reduced if the page is just empty.

2025-11-08

How does the `macro` function in AnQiCMS templates help me reduce redundant rendering logic?

In Anqi CMS template development, improving efficiency and maintaining code cleanliness is the goal that every developer is pursuing.web pages often contain many structurally similar but content-wise different areas, such as each article card in the article list, the various features of a product detail page, or each link item in the navigation menu.If each time you have to rewrite this similar rendering logic, it not only takes time and effort, but also, once you need to make modifications, you may face the dilemma of having to make repetitive changes in multiple places.Luckyly, AnQiCMS's powerful template system provides `macro` macro function

2025-11-08

What role does the `extends` tag play in the AnQiCMS template inheritance system?

In AnQiCMS template development, the `extends` tag plays a core role, it is the key to building efficient, maintainable and structurally unified website templates.The `extends` tag can be understood as creating a bridge between 'master' and 'child pages', allowing you to easily define a common layout skeleton for the entire website without repeating a lot of the same code on each page.

2025-11-08

How to output the current date and time in the AnQiCMS template and specify the format?

Displaying the date and time in the AnQiCMS template in a specific format is a common requirement in website content operations.Whether it is to display the publication time of articles, the deadline of events, or show the current year in the footer, accurate and beautiful time information can enhance the user experience.AnQiCMS provides simple and efficient template tags, allowing you to easily implement these features. Next, we will discuss in detail how to output the current date and time in the AnQiCMS template and specify the format you need.

2025-11-08

How to output variables in a template and safely escape content to prevent XSS attacks?

In the process of managing and displaying website content, ensuring the security of user data is a crucial link.It is an issue that every website operator needs to pay attention to when the website needs to display user submitted content or data obtained from external sources, how to effectively prevent cross-site scripting (XSS) attacks.AnQiCMS (AnQiCMS) took this into full consideration from the very beginning, providing solid security guarantees for content output through its powerful template engine and flexible filter mechanism.### Cross-Site Scripting Attack

2025-11-08