As an experienced website operations expert, I am fully aware of the importance of template development efficiency and code maintainability for a website in my daily work.AnQiCMS (AnQiCMS) leverages its efficient architecture based on the Go language and Django-style template engine to provide us with powerful content management capabilities.includeTags, especially how they help us achieve code reuse and flexibly pass additional variables.
Why do we need code reuse? IntroducedincludeThe meaning of tags
In website operations, we often find that many pages contain the same elements, such as headers (Header), footers (Footer), sidebars (Sidebar), or small components for specific functions (such as article list cards, product display blocks).If you copy and paste this code on every page, it not only creates a huge workload, but also brings about a nightmare-like experience in subsequent maintenance - a minor change may require repeating the operation in dozens or even hundreds of files.
The template design of AnQi CMS fully considers this issue of code redundancy and introducesincludeLabels as solutions.It allows us to extract these general or frequently used code snippets, save them as separate template files, and then reference them where needed.This is like building with blocks, breaking down the website into reusable components, greatly improving development efficiency, reducing maintenance costs, and making the code structure clearer and modular.partial/The catalog, which is designed to store these reusable code snippets.
includeThe basic usage of tags: Modularize your template
includeThe syntax of tags is very intuitive, its basic form is{% include "文件路径" %}. The file path here is relative to the current template directory.
For example, if we have a file namedheader.htmlthat contains the header code for all pages, as well as afooter.htmlfile containing the footer code, then in your main page template (such asindex.htmlordetail.htmlIn the parentheses, you can refer to them like this:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>我的网站</title>
</head>
<body>
{# 引入页眉代码 #}
{% include "partial/header.html" %}
<main>
<h1>欢迎来到我的安企CMS网站</h1>
<p>这是主页内容。</p>
</main>
{# 引入页脚代码 #}
{% include "partial/footer.html" %}
</body>
</html>
By this means,header.htmlandfooter.htmlThe content will be seamlessly inserted into the main template.When the header or footer needs to be modified, we only need to edit these two files, and all pages referencing them will be automatically updated, greatly improving efficiency.
Flexible data transmission: BywithKeyword injection to add extra variables
It may not be enough to be statically included, often, the included segments also need dynamic data to fill.For example, a sidebar component may need to know which category the current page is, or an article card may need to display the title and summary of the article.includelabel'swithKeywords come into play, allowing us to pass some variables to the template being included when we introduce the template.
withThe keyword passes the current template context (all available variables) to the included template and allows you to inject more specific variables on top of that.
The basic syntax is:{% include "文件路径" with 变量名="变量值" %}.
We have a universal article list item templatepartial/archive_item.htmlIt needs to display the article title and link:
{# partial/archive_item.html #}
<div class="archive-item">
<h3><a href="{{ item_link }}">{{ item_title }}</a></h3>
<p>{{ item_description }}</p>
</div>
In our main page template, we can loop through a list of articles and dynamically pass in titles and links for each article:
{# 主页面模板 #}
{% archiveList archives with type="list" limit="5" %}
{% for archive in archives %}
{% include "partial/archive_item.html" with item_title=archive.Title item_link=archive.Link item_description=archive.Description %}
{% endfor %}
{% endarchiveList %}
Here, archive.Title/archive.Linkandarchive.DescriptionIs from the currentforLooparchiveVariable of the object, we pass throughwithThey were assigned toarchive_item.htmlin the templateitem_title/item_linkanditem_descriptionThis way, our component is both general and flexible, able to dynamically render content based on the passed data.
Precisely control the scope:onlyKeyword application
In some cases, we may want the template being introduced to access only the variables we explicitly pass, and not inherit the entire context of the parent template. This requirement can be met byonlyTo implement a keyword. WhenonlywithwithCombined with the use, the template being introduced willOnlyCan access throughwithThe variables passed can be accessed, while the other variables of the parent template are not visible to it.
The syntax is:{% include "文件路径" with 变量名="变量值" only %}.
If we want to ensurepartial/archive_item.htmlonly acceptitem_titleanditem_linkand completely ignore other variables with the same name that may exist in the parent template, we can do this:
{# 主页面模板 #}
{% archiveList archives with type="list" limit="5" %}
{% for archive in archives %}
{% include "partial/archive_item.html" with item_title=archive.Title item_link=archive.Link only %}
{% endfor %}
{% endarchiveList %}
Thus,archive_item.htmlOnly the template inside can use{{ item_title }}and{{ item_link }}This helps to create more independent components that are less affected by the external environment, avoiding potential variable name conflicts and improving the portability of the components.
Robustness consideration: Handling non-existent templatesif_exists
File path adjustments or accidental deletions are common during template development or iteration. If directincludeA file does not exist, the Anqi CMS will report an error and interrupt the page rendering, which is unacceptable in a production environment. To enhance the robustness of the template, we can useif_existskeywords.
Whenif_existswithincludeCombine usage, if the specified file does not exist,includethe tag will be silently ignored without causing an error.
{# 引入页眉代码,如果文件不存在则忽略 #}
{% include "partial/header.html" if_exists %}
<main>
<p>页面核心内容</p>
</main>
{# 引入一个可能不存在的广告组件,并传递数据 #}
{% include "partial/ad_banner.html" with ad_id="promo_summer" if_exists %}
This handling method is especially useful for optional components that do not affect the core functions of the page, ensuring that the website can still operate normally when certain non-core components are missing, and improves the error-tolerant ability of the system.
Summary
includeTags play a crucial role in template development in Anqin CMS. They help us build modular, easy-to-maintain, and efficient website templates through code reuse. CombinedwithKeywords, we can flexibly inject dynamic data into these reusable components;onlyKeywords provide precise control over variable scope, ensuring the independence of components; andif_existsThe keyword provides a guarantee of the robustness of the template.Master and make good use of these features, and it will make your safe CMS website development experience more smooth, code quality higher, and operation efficiency even better.
Frequently Asked Questions (FAQ)
includeandextendsWhat are the differences between tags?extendsThe tag is used to implement template inheritance, it defines a basic skeleton (parent template), and child templates can overwrite specific "blocks" defined in the parent template (block)extendsUsed to define the overall layout of the page and must be the first tag in the sub-template. AndincludeTags are used to insert other template fragments anywhere to achieve local code reuse. It does not involve template inheritance relationships but simply inserts the file content at the current position. You can understand it asextendsIt is 'I inherited your genes, but may have changed your eye color,' andincludeIt is 'I transplanted your nose onto my face.'includeCan the template that is introduced use variables from the parent template?Yes, by default,includethe template introduced will automatically inherit all variables from the parent template. This means that any variable defined in the parent template, will beincludeThe child fragments are all accessible and usable. Of course, if you only want to pass specific variables, you can usewith ... onlySyntax is used to limit this inheritance to ensure that the template being imported only accesses explicitly passed variables.When should it be used
includeAnd when should it be usedmacro?includeandmacroare