In website operation, maintaining the modularity and high reusability of content can not only significantly improve development efficiency, but also make the website more flexible during iterative updates.Auto CMS (AutoCMS) provides an intuitive and efficient solution to achieve this goal with its powerful template engine.This article will delve into how to utilize the template mechanism of the AnQi CMS to cleverly reference external HTML fragments, such as headers and footers, thereby building a website that is easy to manage and has a clear structure.
模块化内容的价值:为何要引用外部HTML片段?
Imagine a website with dozens, even hundreds of pages. If each page needs to be individually written for headers, footers, navigation bars, and other common sections, then any minor change will mean a huge amount of work.The modular content, as the name implies, is to extract the common components of a website (such as headers, footers, sidebars, navigation menus, etc.) and manage them as independent HTML files.When these modules need to be updated, we only need to modify one place, and all pages that refer to this module will be automatically synchronized, which greatly improves the maintenance efficiency, design consistency, and ease of teamwork of the website.The template mechanism of Anqi CMS is designed to meet such needs.
模块化内容的价值:为何要引用外部HTML片段?
The template engine of Anqi CMS is similar to Django, it uses.htmlfiles as templates, and they are stored uniformly in the root directory of the website./templateThe folder design makes the template files clear at a glance, convenient for management. In the Anqi CMS, the core tool for implementing HTML fragment references is its built-in template tags, especiallyincludeandextendsThey are the foundation for building modular websites.
includeTags: Embed reusable HTML fragments
includeThe role of a label is to embed an independent template file (or what is called a "code snippet") into another template file.This is the most direct way to implement modularization of common areas such as header, footer, sidebar, etc.
For example, you usually save the header part of the website (including the logo, navigation bar, website title, etc.) as apartial/header.htmlfile, and save the footer information aspartial/footer.htmlFile. When you need to display these common parts on any page, just add the following code to the main template of the page:
{% include "partial/header.html" %}
<!-- 页面主体内容 -->
{% include "partial/footer.html" %}
This is,header.htmlandfooter.htmlThe content inside will be 'pasted' into the current position at runtime.
includeThe tag also provides additional flexibility:
- Optional import
if_exists: If you are not sure if a certain fragment file exists, you can use{% include "some_optional_file.html" if_exists %}If the file does not exist, the system will not report an error, but simply ignore it, which is very useful in some dynamic or optional module scenarios. - Pass variables
withSometimes, you may need to pass some specific data to the imported segment.includeTags allow you to usewithkeywords to pass variables. For example:{% include "partial/sidebar.html" with title="最新文章" count=5 %}.sidebar.htmlin it, you can use it directly.{{title}}and{{count}}Get these values.
PassincludeYou can easily split the various general components of the website into independent, maintainable files, greatly enhancing the reusability and modification efficiency of the content.
extendsandblock标签:Build page skeleton and content filling
Compared withincludeof the “Embed”,extendsLabels provide a more powerful modular capability - template inheritance.It allows you to define a basic page layout (usually referred to as a 'master' or 'skeleton'), and then let other pages inherit this layout while only filling or modifying specific areas within it.
a typicalbase.html(Master Template) may include the following structure:
<!DOCTYPE html>
<html lang="{% system with name='Language' %}">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% tdk with name="Title" siteName=true %}{% endblock %}</title>
<!-- 其他公共头部元素,如CSS、JS等 -->
</head>
<body>
{% include "partial/header.html" %} {# 引入公共页头 #}
<main class="container">
{% block content %}
<!-- 子页面将在这里填充主要内容 -->
{% endblock %}
</main>
{% include "partial/footer.html" %} {# 引入公共页脚 #}
</body>
</html>
in thisbase.htmlIn:
{% block title %}and{% block content %}Defines areas that can be overridden or filled by child templates.- Unspecified
blockThe part wrapped by the label (such as<!DOCTYPE html>/<html>, common CSS/JS,include "partial/header.html"/include "partial/footer.html"etc.) will be common to all pages inheriting this master template.
Now, if your article detail page needs to use this layout, you can create onearchive/detail.htmlfile and write it like this:
{% extends 'base.html' %} {# 声明继承自 base.html,此标签必须是子模板的第一个标签 #}
{% block title %}
<title>{% archiveDetail with name="Title" %} - {% system with name="SiteName" %}</title>
{% endblock %}
{% block content %}
<article>
<h1>{% archiveDetail with name="Title" %}</h1>
<div>
<!-- 文章的具体内容和信息 -->
{% archiveDetail with name="Content" render=true|safe %}
</div>
</article>
{% endblock %}
This is,archive/detail.htmlthen it inheritsbase.htmlthe overall structure, and only overrides the page'stitleandcontentArea. When you visit the article detail page, it will automatically combinebase.htmlandarchive/detail.htmlthe content for rendering.
Template directory structure: clear management of modular files
In order to better organize these modular HTML fragments, adhering to a clear directory structure is crucial.The auto CMS provides two template organization modes: folder organization mode and flattened file organization mode.No matter which one you choose, the key is to put the common, reusable segments in a dedicated directory.
通常,建议在您的模板目录下创建一个名为 Englishpartial/的子目录,用于存放所有可被 Englishinclude的公共HTML片段,例如 Englishpartial/header.html/partial/footer.html/partial/navigation.html等。而作为页面骨架的 Englishbase.htmlIt can be placed directly in the root directory of the template.
Passing and rendering dynamic data
In modular templates, you can still make full use of the various tags provided by the Anqi CMS to obtain and render dynamic data. WhethersystemTags retrieve basic information about the website.navListLabel to get navigation menu, orarchiveListLabel to get article list, they can all be displayed in anyincludeorextendstemplate fragment. For example, yourpartial/header.htmlmay contain{% navList navs %}Generate navigation menu dynamically.
Summary
AnQi CMS through its flexible template engine, especiallyincludeandextendsThese powerful tags provide comprehensive support for the modular display of website content.Reasonably utilizing these features can not only make your website development and maintenance more efficient, but also ensure that the website maintains a high level of consistency in both visual and functional aspects.Abstracting common elements into reusable modules and then building pages through inheritance and embedding is the key strategy for creating high-quality, scalable websites.
Common Questions (FAQ)
1. Where should I place the CSS and JavaScript of the HTML snippet I am introducing?
base.htmlof<head>or<body>Bottom. For custom styles and scripts of specific modules (such as headers, footers, sidebars), you can choose:
- Inline to the fragment file: In
partial/header.htmlit directly inside<style>and<script>Label. This applies to small amounts of code that are highly coupled with the segment. - As an independent file imported: In
base.htmlThe use of conditional judgment or direct linking to introduce external CSS/JS files related to a specific module. For example, ifpartial/header.htmldependenciesheader.css, you canbase.htmlof<head>introduce it in. - Packaging and optimization:A more advanced approach is to bundle and compress all CSS/JS files related to modules, reduce HTTP requests, and
base.htmlunify the introduction of optimized files.
2.includeandextendsWhat are the differences, when should I use which?
includeSuitable forEmbeddedReusableIndependent code snippet.It is more like copy and paste, directly inserting the content of a file into the current position.For example, headers, footers, widgets, ad slots, and so on, these fragments do not define the complete page structure by themselves, but are just part of the page.extendsSuitable forDefine the page skeleton and fill in the contentIt is an inheritance relationship, where the child template inherits the overall layout of the parent template and then overrides the definitions in the parent template.blockarea.extendsEnglish for '通常用于构建整体页面布局,例如所有页面都拥有相同的页头、页脚、侧边栏,但中间的内容区域各不相同。' is 'It is commonly used to build the overall page layout, for example, all pages have the same header, footer, and sidebar, but the content area in the middle is different.
In short:
- English for '当您需要在一个页面中' is 'When you need to place something on a single page'InsertWhen a complete, independently running UI component is needed,
include. - When you need to define a unified layout structure for the entire website or a certain type of page,a unified layout structure,and allow sub-pages to customize some parts of it when
extends.
3. How should I operate if I need to pass dynamic data to the imported fragments?
When you use{% include "partial/some_fragment.html" %}imported whensome_fragment.htmlThe default will inherit all the context variables of the current main template. This means that any variable defined in the main template can be used directly in the fragment.
If you need to passadditionaloroverrideThe data of the existing master template variables can be usedwithKeyword:
{# 在主模板中 #}
{% set page_title = "首页" %}
{% include "partial/header.html" with current_nav_item="home", welcome_message="欢迎来到我们的网站!" %}
Inpartial/header.htmlIn it, you can access these variables like this:
<h1>{{ welcome_message }}</h1>
<nav>
<a href="/" {% if current_nav_item == "home" %}class="active"{% endif %}>首页</a>
{# ... 其他导航项 #}
</nav>
<p>当前页面标题: {{ page_title }}</p> {# 仍然可以访问主模板的变量 #}
Please note that, usingwithThe priority of the passed variables is higher than that of the same-named variables in the master template, but only in theincludeThe scope of the statement is valid. If you want to pass only specified variables without inheriting other variables from the main template, you canwithafter addingonlykeywords.