How to include external HTML fragments in AnQiCMS templates?

Calendar 👁️ 55

When building website templates in AnQiCMS, we often encounter some HTML code blocks that need to be reused, such as the website header, footer, sidebar navigation, ad spaces, or some general content modules.If you always repeat writing this code in different template files, it is not only inefficient, but also very麻烦 once you need to modify it, you have to search and update each file one by one, and it will be very difficult to maintain.

To solve this problem, AnQiCMS provides powerful template functions, including the ability to introduce external HTML fragments, making the development of website templates more flexible and efficient.

Core feature: easily introduce external HTML fragments

The AnQiCMS template system is based on syntax similar to Django, which allows you to useincludeThe tag, which embeds the content of an independent HTML file into another template file.The core value of this feature lies in 'reusability', you can extract those common parts that need to be displayed on multiple pages, make them into a separate HTML file, and then simply refer to them in the places needed.

Generally, these reusable HTML snippet files are named with.htmlsuffixes and are recommended to be stored in your template directory underpartial/subfolders. For example, you have a folder nameddefaultThe template, its root directory is/template/default/Then you can create a/template/default/partial/directory, specifically used to store these code snippets.

The most basic inclusion method is very intuitive, like this:

{# 假设您的模板文件是 index.html #}

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

<main>
    <h1>欢迎来到我的网站</h1>
    <!-- 这里是页面特有的内容 -->
</main>

{% include "partial/footer.html" %}

In the above example,header.htmlandfooter.htmlThese are two external HTML fragments. They may contain the website's logo, main navigation, copyright information, and other common elements.

A simplepartial/header.htmlIt might look like this:

<header class="site-header">
    <div class="container">
        <a href="/" class="logo">
            <img src="/static/images/logo.png" alt="网站Logo">
        </a>
        <nav class="main-nav">
            <ul>
                <li><a href="/">首页</a></li>
                <li><a href="/about">关于我们</a></li>
                <li><a href="/contact">联系我们</a></li>
            </ul>
        </nav>
    </div>
</header>

This way, no matter which page needs a header, it only takes a line{% include "partial/header.html" %}and it can be done, greatly improving development efficiency and the convenience of later maintenance

Advanced usage: passing data to fragments

At times, the HTML fragments introduced are not just static content, they may also need to display some dynamic information.For example, a sidebar may need to display the title of the current page, or a generic card component may need to be filled with different data.AnQiCMS allows you to useincludewhen using tags, bywithThe keyword passes a variable to the inserted segment.

For example, you might have apartial/sidebar.htmlIt needs onecurrent_titleA variable to display the current page information:

<aside class="sidebar">
    <h3>当前页面</h3>
    <p>{{ current_title }}</p>
    <ul class="recent-posts">
        <!-- 这里可能还有其他动态内容,比如最新文章列表 -->
    </ul>
</aside>

In your main template file, you can do this to passsidebar.htmlPass data:

{# 假设您的模板文件是 article_detail.html #}

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

<main>
    <h1>文章详情页</h1>
    <div class="content">
        <!-- 文章内容 -->
    </div>
</main>

{% include "partial/sidebar.html" with current_title="AnQiCMS模板开发指南" %}

{% include "partial/footer.html" %}

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

{% include "partial/product_card.html" with product_name="AnQiCMS企业版" price="¥999" discount="8折" %}

In some cases, you may want the snippet to only access the variables you explicitly pass and not access other variables in the main template. In this case, you canwithAdd afteronlyKeyword:

{% include "partial/ad_banner.html" with ad_id="promo_123" ad_type="image" only %}

usedonlyafter,ad_banner.htmlonly usead_idandad_typeThese two variables will not be affected by other variables in the main template, which helps to maintain the independence of code segments and avoid potential naming conflicts.

Handle non-existent template files

During development, you occasionally encounter situations where the template file path is incorrect or the file has been deleted, which may cause the page to report errors. To improve the robustness of the template, you can useif_existskeywords.

When you useif_existsIf the specified template file does not exist, AnQiCMS will gracefully ignore thisincludeSentences that will not cause the entire page to render failed. This is particularly useful in some non-core, optional code snippets.

{# 尝试引入一个可能存在的广告位,如果不存在也不会报错 #}
{% include "partial/optional_ad.html" if_exists %}

<main>
    <h1>页面主内容</h1>
</main>

{# 尝试引入一个可能存在的推荐文章模块 #}
{% include "partial/recommended_articles.html" if_exists with category_id="1" %}

Use tips with **practice

  • Modular thinking:When designing a template, try to divide the page into logical and functionally independent modules, each corresponding to a HTML fragment.
  • Clear directory structure:Always recommend placing all reusable fragments in a unifiedpartial/directory and further subdividing according to function, for examplepartial/nav/main_menu.html,partial/widgets/search_box.html.
  • Avoid excessive nesting:Although it can be nested infinitelyincludeBut deep nesting may make the template structure complex, which is not conducive to understanding and debugging. Try to keep the fragments flat.
  • Reasonable useextendswithinclude: extendsTags are usually used to define the overall layout skeleton of the page (such asbase.html), including the header, sidebar, main content area, and other large structures, andincludeIt is used to fill or insert specific components or content blocks into these structures. Both complement each other, jointly building an efficient template system.
  • Add comments to the segment:Add a brief comment at the beginning of the complex fragment file, explaining its function, required variables, etc., to facilitate teamwork and future maintenance.

By cleverly using AnQiCMS'sincludeFunction, you can make the website template development more organized, easy to manage, and significantly improve development and maintenance efficiency.


Frequently Asked Questions (FAQ)

1.includeandextendsWhat are the differences between tags?

extendsThe tag for implementing template inheritance, it defines the overall skeleton or layout of a page and allows child templates to overwrite specific "blocks" (block). Usually, a page will onlyextendsA parent template.includeThe tag is used to insert an independent HTML snippet in any template (including parent and child templates).This can be understood as copying and pasting a small code file to the current location.extendsIt defines the "shape" of the page.includeIt fills the page with "content blocks".

Can I use AnQiCMS tags and variables in the introduced HTML snippet?

Certainly, it can be done. The AnQiCMS template system passes the context of the current template (all available variables and tags) to the beingincludefragment. This means you canincludeIn the fragment, as in the main template, freely use various tags provided by AnQiCMS (such asarchiveList/system) and variables passed to the fragment or inherited from the parent template.

3. The HTML fragment file must be placed inpartial/the directory, is that correct?

It is not necessary, this is a recommended practice. You can place the HTML fragment file in any subfolder of the template directory, as long asincludeThe path provided in the tag is the correct path relative to the current template directory. For example, if your snippet is inmy_components/widget.html, then you can write{% include "my_components/widget.html" %}. But in order to maintain the clarity of the project structure and facilitate management, it is strongly recommended to classify commonly used segments uniformly topartial/directory.

Related articles

What is the difference between the variable output and logic control tags in AnQiCMS templates?

In AnQiCMS template development, we often deal with two core template elements: variable output tags and logical control tags.They all serve to present dynamic content to the user, but there are essential differences in their functional positioning, syntax form, and actual effects.Understanding and mastering their similarities and differences is the key to efficiently building AnQiCMS website templates.### Variable output label (`{{ ... }}`): The direct window for data display Imagine that your website is a beautiful showcase, and the variable output label is like the merchandise displayed in the showcase

2025-11-07

How to write AnQiCMS templates according to Django template engine syntax rules?

AnQiCMS (AnQiCMS) is an efficient and customizable content management system, with its powerful template engine being the core for achieving diverse website presentations.The template engine adopted by the system is highly similar to Django's syntax rules, which allows users familiar with web development to get started faster, even beginners can gradually master the skills of template writing through the guidance of this article.

2025-11-07

How to use AnQiCMS template tags correctly to avoid common errors?

AnQiCMS provides a powerful and flexible template system, allowing the display of website content to be highly customizable.The syntax of its template tag language draws inspiration from the Django template engine and integrates the ease of use of Blade templates, making it easy for users unfamiliar with the Go language to get started.However, to fully utilize the potential of template tags and avoid common mistakes, it is crucial to understand their correct usage and potential pitfalls.### AnQiCMS Template Tag Basics: Understanding Core Syntax and Conventions AnQiCMS template files are usually formatted with `

2025-11-07

Does the statistics code tag support loading based on user role or login status?

In website operation, data statistics is the core to understand user behavior, optimize content strategy, and improve conversion rate.However, not all user data needs to be tracked in the same way, especially for internal team members, administrators, or specific VIP users, where we may want to avoid mixing their behavioral data into public-facing statistical reports or load statistical codes for specific user groups due to privacy considerations.For AnQi CMS users, a common and very practical question is: Can we flexibly decide whether to load the page statistics code based on user roles or login status?

2025-11-07

How to implement page skeleton reuse through inheritance in AnQiCMS templates?

In website construction and operation, we often face a challenge: how to ensure the consistency of the overall style of the website while being able to flexibly modify the specific content of each page, and at the same time, taking into account the development efficiency and the convenience of later maintenance?AnQiCMS provides a powerful and intuitive template inheritance mechanism, which is the core of solving these problems.It's like creating a "template" for your website, allowing you to easily reuse common structures and focus on content creation.

2025-11-07

What are the application scenarios of AnQiCMS template macro functions (macro) and include tags?

In AnQiCMS template development, in order to improve code reusability and reduce maintenance costs, we often use some powerful template functions, among which 'macro function' and 'Include tag' are two great assistants.They each have unique advantages and applicable scenarios. Understanding and appropriately applying them can make template development twice as efficient and build efficient, easy-to-maintain websites.

2025-11-07

How to display the current time and formatted timestamp in AnQiCMS template?

Displaying time on the website content, whether it is the publication date of the article, the update time of the product, or the real-time loading time of the page, can greatly enhance the user experience and the timeliness of information.AnQiCMS is a content management system developed based on the Go language, which is very intuitive and flexible in handling time and dates in templates.This article will introduce you to how to display the current time and formatted stored timestamp in AnQiCMS templates.

2025-11-07

How to customize variables and assign values using (with/set) in AnQiCMS templates?

In AnQiCMS templates, flexibly customizing and using variables is the key to achieving dynamic content and efficient template reuse.AnQiCMS's template syntax borrows the characteristics of popular template engines such as Django and Blade, making variable definition and assignment intuitive and powerful.This article will deeply explore the `with` and `set` tags, helping you to better customize variables and utilize them in AnQiCMS templates.### One, the foundation of variable customization: Understanding the core of template syntax In AnQiCMS template

2025-11-07