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 to solve these problems.It's like creating a 'master template' for your website, allowing you to easily reuse common structures and focus on content creation.
Understanding the core principle of template inheritance
In simple terms, AnQiCMS's template inheritance feature allows us to define a basic page layout, which we call the "page skeleton" or "parent template", containing the common structural elements of all web pages, such as headers, footers, navigation bars, sidebars, etc. Within this skeleton, we will go through{% block ... %}Label some 'variable areas'. Sub-templates then inherit this framework and can use the same-named{% extends '父模板路径' %}to inherit this skeleton and can use the same-named{% block ... %}Label to fill or rewrite the reserved area in the parent template. The areas that the child templates do not rewrite will automatically follow the content in the parent template.
This mechanism is similar to the "slide master" in presentation software: the master defines the overall layout and design, while each slide fills in specific content.The benefits of doing so are obvious: the public elements of the website are maintained统一, while the unique content of the page can be freely customized.
Build your page skeleton: the design of the parent template.
To utilize template inheritance, you first need to create a base parent template, usually namedbase.html, and place it in the root directory of the template directory. Thisbase.htmlIt will carry the most basic HTML structure of your website, for example,<!DOCTYPE html>/<html>/<head>and<body>Label.
Inbase.htmlIn it, you can arrange general elements:
- Header navigation area: Usually includes Logo, main navigation, search box, etc.
- Page main layoutFor example, the left sidebar, content area on the right, and so on.
- Footer information: Including copyright statement, filing number, friendly links, and so on.
You need to use in these fixed structures,{% block ... %}Define those areas that may change across different pages. For example, you can define atitleblock for the page title, acontentBlock for the main content of the page orstyles/scriptsBlocks for introducing page-specific styles or scripts.
`twig {# template/base.html #} <!DOCTYPE html>
<meta charset="UTF-8">
{# 页面标题,子模板可重写 #}
{% block title %}<title>我的网站</title>{% endblock %}
{# 额外meta信息,子模板可重写 #}
{% block meta %}{% endblock %}
<link rel="stylesheet" href="/public/static/css/common.css">
{# 页面特有样式,子模板可重写 #}
{% block styles %}{% endblock %}