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

Calendar 👁️ 64

Building website templates in AnQiCMS, efficient code reuse is the key to improving development speed and maintenance efficiency.Imagine that 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 page by page, which is undoubtedly a huge amount of work.include.

AnQiCMS template engine is similar to Django syntax, it aims to make template creation simple and easy to understand. ByincludeLabel, you can easily extract common code segments such as headers, footers, sidebars into independent files, and then reference them where needed, greatly simplifying the structure and management of templates.

Why choose code reuse?

Efficient code reuse can bring various benefits. The first isimprove development efficiencyYou do not need to rewrite the same HTML structure, CSS links, or JavaScript references on each page.Use only once, and it can be used multiple times throughout the site.website consistencyNo matter how many pages your website has, the style and function of the common part can be kept uniform. The most important thing isSimplify maintenance workWhen the website's logo, navigation menu, or copyright information needs to be updated, you only need to modify a single public file, and all pages that reference this file will be updated synchronously, greatly reducing the risk of errors and maintenance costs.

includeBasic usage of tags

Template files in AnQiCMS are usually named with.htmlsuffix and stored in/templateIn a specific subject folder under the directory. To better organize code snippets, you can create apartial/subdirectory to store those that areincludequoted public snippets, such asheader.html/footer.htmletc.

includeThe tag syntax is very straightforward:

{% include "文件路径" %}

Here文件路径It is relative to the root directory of your template (for example/template/您的主题名/).

For example, if you want to introduce a location inindex.htmlinsidepartial/header.htmlThe header and located atpartial/footer.htmlThe footer, your code might look like this:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>我的网站首页</title>
    <!-- 其他头部元信息和样式表 -->
</head>
<body>

    {# 引入页头公共代码 #}
    {% include "partial/header.html" %}

    <main class="content">
        <h1>欢迎来到我的AnQiCMS网站!</h1>
        <p>这里是网站的主要内容区域。</p>
        <!-- 更多页面特有内容 -->
    </main>

    {# 引入页脚公共代码 #}
    {% include "partial/footer.html" %}

</body>
</html>

and in thepartial/header.htmlfile, you may have defined navigation bars, logos, and other elements:

<header class="site-header">
    <div class="logo">
        <a href="{% system with name="BaseUrl" %}">
            <img src="{% system with name="SiteLogo" %}" alt="{% system with name="SiteName" %}">
        </a>
    </div>
    <nav class="main-nav">
        <ul>
            {% navList navs %}
            {%- for item in navs %}
                <li class="{% if item.IsCurrent %}active{% endif %}">
                    <a href="{{ item.Link }}">{{item.Title}}</a>
                </li>
            {% endfor %}
            {% endnavList %}
        </ul>
    </nav>
</header>

partial/footer.htmlFiles may contain copyright information, filing numbers, etc.

<footer class="site-footer">
    <p>{% system with name="SiteCopyright" %}</p>
    <p><a href="https://beian.miit.gov.cn/" rel="nofollow" target="_blank">{% system with name="SiteIcp" %}</a></p>
</footer>

By this method, your main page files (such asindex.htmlIt will become very concise, focusing on the unique content of the page, while the common part is handled by each file.

Pass data to the template that is included.

Sometimes, you may want to beincludeThe template can receive some specific data to display content more flexibly. AnQiCMS'sincludetags support usingwithkeywords to pass variables.

For example, you may want the page header to display different titles based on the current page, but the page header file itself does not have the ability to retrieve the page title. In this case, you can passincludeat the time:

{% include "partial/header.html" with page_title="关于我们" %}

Inpartial/header.htmlIn Chinese, you can use thispage_titleVariable:

<header class="site-header">
    <h1>{{ page_title }}</h1> {# 这里会显示“关于我们” #}
    <!-- ... 其他页头内容 ... -->
</header>

You can also pass multiple variables, just separate them with spaces:

{% include "partial/header.html" with page_title="关于我们" show_search="true" %}

By default, theincludeThe template inherits all available variables from the current template. If you only want the included template to use variables passed throughwithand ignore all other inherited variables, you can useonlyKeyword:

{% include "partial/header.html" with page_title="关于我们" only %}

Handle the possibility of a non-existent template

To avoid beingincludecaused by the non-existent template file leading to page errors, you can useif_existskeywords. When the template file being referenced does not exist,if_existsIt will tell the system to ignore thisincludeThe operation, rather than throwing an error. This is very useful in some optional, non-core module references.

{# 如果存在这个文件则引入,不存在则忽略 #}
{% include "partial/sidebar.html" if_exists %}

By flexible applicationincludeTags and their various parameters, you can build a clear, easy to manage and efficient AnQiCMS website template.


Frequently Asked Questions (FAQ)

1.includeTags andextendsWhat are the differences between tags, and how should they be used together?

includeThe tag is mainly used to insert small, reusable code snippets (such as headers, footers, sidebars) into the current template, focusing on the insertion of local components. AndextendsTags are used to implement template inheritance, it defines a basic layout skeleton (base template), other templates can inherit this skeleton and only modify specific "blocks" (block)。In actual development, these two are often used together: You can useextendsto define a structure that includes the header, footer, and main content areabase.htmlskeleton, and thenbase.htmluse it insideincludeThe label introduces independent header and footer files, which can maintain the uniformity of the overall layout and realize the flexible reuse and management of local components.

2. Can IincludeUse AnQiCMS built-in tags (such as{% system %}or{% navList %}) right?

Of course, it can be.includeThe file is essentially still an AnQiCMS template file. Therefore, you can freely use all the built-in tags and variable outputs provided by AnQiCMS ({{变量名}})and conditional judgment({% if %})and template syntax. This allows you to dynamically obtain system configurations, navigation lists, and other information in common code snippets, achieving high flexibility.

3. If myincludeIf the file path is wrong or the file does not exist, will the page report an error? How to avoid it?

Yes, ifincludeThe specified file path in the tag is incorrect or the file does not exist, AnQiCMS will throw an error while rendering the page, causing the page to not display normally. To avoid this situation, you can useif_existsKeyword. For example:{% include "partial/non_existent_file.html" if_exists %}So, ifnon_existent_file.htmlIf the file does not exist, the system will skip this.includeOperation will not cause an error, the page will still load normally, but the corresponding content will not be displayed. This is particularly useful for some optional, non-essential template fragments.

Related articles

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 to implement reverse or custom sorting output of AnQiCMS's `for` loop?

The order of website content listings is crucial for user experience and information delivery.Whether it is news updates, product displays, or article archives, flexibly controlling the output order of lists is a common demand in website operation.AnQiCMS provides a powerful and easy-to-use template engine, allowing us to easily control the arrangement of lists, including reverse order and sorting by specific rules.### AnQiCMS Template Engine Basics The AnQiCMS template system adopts the syntax style of the Django template engine, using concise tags and variable declarations

2025-11-08

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

Advanced AnQiCMS Template: `include` Sub-template Data Passing Techniques and Practices In AnQiCMS template development, the `include` tag is undoubtedly a powerful tool for enhancing template reusability and modularization.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 question: how to introduce sub-templates at the time

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