How to include external HTML fragments in AnQiCMS templates?

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.