How to use AnqiCMS template include tag to introduce common code fragments and achieve page structure reuse?

Calendar 👁️ 73

In website content management, we often encounter situations where we need to display the same content blocks, such as headers, footers, sidebars, or navigation menus, on multiple pages.If you copy and paste this code every time, it is not only inefficient, but also face the繁琐 of repeated operations in multiple files when you need to modify it.If this continues, the maintenance and update of the website content will become extremely difficult, and it may even lead to inconsistent experiences.

幸运的是,AnqiCMS(AnqiCMS)为我们提供了一个优雅的解决方案,其核心就是它模板引擎中的include 标签。通过巧妙地运用includeLabel, we can easily implement the introduction of common code snippets and the reuse of page structures, thereby greatly enhancing the development and maintenance efficiency of the website.

Get to knowincludeThe core role of tags

includeThe essence of a tag is to allow you to include another independent HTML file or code snippet within a template file.This is like building a Lego model where you don't have to build the same part from scratch every time, but can assemble some common components in advance and use them directly when needed.partial/in the folder, for example, the header can bepartial/header.htmlThe footer can bepartial/footer.html.

The benefits of doing this are obvious:

  1. code centralized management: All public code needs to be written once and stored in one place.
  2. Maintenance is convenient and efficientWhen the public part needs to be adjusted, only one file needs to be modified, and all pages that refer to it will be synchronized for updates, avoiding omissions and inconsistencies.
  3. Clear and readable structure:Split the page into independent logic blocks to make the template structure clearer, easier to understand and manage.

Flexible applicationinclude:From basic introduction to dynamic content

UseincludeThe tag is very intuitive, the most basic usage is to specify the file path to be imported, for example:

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

Thus,header.html/sidebar.htmlandfooter.htmlThe content will be "embedded" into the current template file.

However, simply static introduction is sometimes not enough to meet complex needs.We may want the same header fragment to display different titles on different pages, or the sidebar to load different content based on the current page type.includeTag provided.withandonlyThe parameters come into play.

  1. BywithPassing variables

    By default, theincludeThe template fragment will inherit all variables from the current template environment. But if you want to pass some specific data to the imported fragment, you can usewithParameters. This allows you to make common fragments more dynamic and general.

    For example, a universal header fragment may need to display a dynamic page title and keywords:

    {% include "partial/header.html" with title="当前页面标题" keywords="SEO关键词" %}
    

    and in thepartial/header.htmlIn, you can use these passed variables like this:

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>{{title}} - {% system with name="SiteName" %}</title>
        <meta name="keywords" content="{{keywords}}">
        <!-- 其他页头内容 -->
    </head>
    <body>
    

    BywithWe can provide customized data for each introduced segment flexibly, without modifying the segment itself.

  2. UseonlyControl variable scope

    Although inheriting all variables is convenient, in some cases, we may want to beincludeonly access the fragment throughwithClearly pass the variable without inheriting other variables from the current template environment.This helps to avoid potential variable conflicts or unnecessary dependencies, making the segment more independent and controllable.withadded after the parameteronly:

    {% include "partial/header.html" with title="当前页面标题" keywords="SEO关键词" only %}
    

    Now,partial/header.htmlAccess will be restricted totitleandkeywordsThese two variables, while unable to access any other variables defined in the current page.

  3. Utilizeif_existsElegantly handle the non-existent segment.

    Sometimes, the template snippet you introduce may not be necessary for every page, or you may not be sure whether a snippet has been created during the development process.Directly including a non-existent file will cause the template to render an error.if_existsparameters:

    {% include "partial/optional_ad_section.html" if_exists %}
    

    Ifpartial/optional_ad_section.htmlThe file exists, it will be imported; if it does not exist, the Anqi CMS will silently ignore thisincludecommand without throwing an error, ensuring the normal rendering of the page.

Advanced modular management:extendsandmacro

exceptincludeLabel, the Anqi CMS template system also providesextendsandmacroLabels, they have different focuses on code reuse, together building a powerful template system

  • extendsTag: If said thatincludeIs "insert part", thenextendsIt is "inherit skeleton".extendsUsed to define the overall layout of the page or "master", usually containing the page's HTML structure, general CSS/JS references, and some placeholders (block),供子模板填充具体内容。例如,你可以定义一个base.html作为所有页面的基础布局,其中定义了header/content/footeretcblockarea.
  • macroTag:macroIt is more like a 'function' in programming language.It allows you to define small, reusable HTML code blocks with parameters.macro会比includeMore flexibility. For example, one used to render an article list item.macroCan receive an article object as a parameter and generate the corresponding HTML accordingly.

By usingincludeUsed for independent code snippets,extendsUsed for overall page layout, as well as,macroUsed for parameterized repeated structures, we can organize website templates neatly, maximize code reusability, and focus on high-quality content creation and website operations.These templates provided by Anqi CMS make website maintenance more efficient and intelligent.


Frequently Asked Questions (FAQ)

Q1:includeTags andextendsWhat is the difference between tags, and how should I choose?

A:includeThe tag is used to "insert" another template fragment at any position in the current template, just like pasting a picture onto a canvas. It is suitable for reusing independent, functional code blocks, such as navigation menus, sidebar widgets, etc. AndextendsThe tag is used to define the overall layout or "skeleton" of the page, it must be the first tag in the template file, allowing sub-templates to "inherit" and fill in the definitions in the parent template.blockArea. Simply put,extendsIt is a top-down structural inheritance, defining what should be here,includeIs a horizontal component insertion, defining 'Here is something needed'. When you want to reuse the overall page layoutextends, when you want to reuse a small piece of codeinclude.

Q2: Can I use the current page's data (such as the document title) in the template snippet I introduced?

A: Yes. By default, you canincludeThe template fragment introduced by the tag will automatically inherit all variables from the current template environment. This means that inheader.htmlyou can directly access the current page's{{archive.Title}}Or{{category.Description}}data is present, assuming that these variables exist in the current template context. If you want to control more precisely which variables can be accessed, you can usewithandonlyParameters to specify or limit.

Q3: If I want toincludePass some variables dynamically into the template snippet without wanting it to access all the variables of the current page, what should I do?

A: You can usewithparameters to pass specific variables, andwiththen addonlykeywords. For example:{% include "partial/my_component.html" with item_id=123 item_name="示例" only %}Thus,my_component.htmlthe template can only accessitem_idanditem_nameThese variables, without inheriting any other variables from the current main template, thus achieving stricter scope control and modularization.

Related articles

How to use with or set tags in AnqiCMS templates to define variables for optimizing content display and maintenance?

In AnqiCMS template development, defining and using variables are indispensable skills to make our website content more flexible and code easier to maintain.The system uses a syntax similar to the Django template engine, where `with` and `set` tags are used to define variables, optimizing content display and managing templates effectively.Understanding and using them effectively can make your website operation twice as effective.Why do we need to define variables in the template?

2025-11-09

How to format a timestamp in AnqiCMS template to display a custom date and time format?

In AnqiCMS, managing website content, we often need to display the publication time, update time, or registration and login time of users, etc.These time information is usually stored in the database in the form of a timestamp, which is a series of numbers.If displayed directly on the website front end, these numbers are not intuitive and lack aesthetics.Fortunately, AnqiCMS provides very flexible template tags, allowing us to easily format these timestamps into the date and time display format we want.AnqiCMS template system

2025-11-09

How to iterate through data using the for loop tag in AnqiCMS templates and display list content on the front end?

In modern website construction, content lists are everywhere, whether it is article lists, product displays, user comments, or navigation menus, they cannot do without efficient organization and presentation of data.AnqiCMS as an enterprise-level content management system based on Go language, provides intuitive and powerful loop tags in template creation, allowing you to easily display various list content on the front page.

2025-11-09

How does the AnqiCMS template use if/else tags for conditional judgments to dynamically display different content?

In website content operation, we often need to flexibly display different content modules or styles based on different conditions to enhance user experience and page interactivity.AnqiCMS (AnqiCMS) provides powerful template tag features, among which the `if/else` conditional judgment tags are the core tools to achieve this goal.By it, we can easily make the website content come to life according to specific rules, no longer monotonous static display.### AnqiCMS template basic conditional judgment: `if`

2025-11-09

How to implement template inheritance using the extends tag in AnqiCMS templates to unify the visual style of the website?

In website operation, maintaining a consistent visual style is the key to brand image and user experience.Imagine if every page layout on your website was different, with navigation positions changing back and forth, users would feel confused and even lose interest.Fortunately, AnqiCMS provides a powerful and elegant way to solve this problem - that is through the `extends` tag in the template inheritance mechanism.AnqiCMS has adopted a template engine syntax similar to Django, making template development intuitive and efficient.

2025-11-09

How does AnqiCMS ensure that mathematical formulas and flowcharts can be displayed correctly on the front end after enabling the Markdown editor?

Today, with the increasing diversity of content creation, websites not only carry text and images, but also often need to display complex mathematical formulas or intuitive flowcharts.For those who use AnqiCMS, the good news is that the system has built-in powerful Markdown editor support, and with simple configuration, it can ensure that these professional contents are perfectly presented on the website front-end.Below, let's take a look at how to operate, making your website content richer and more professional.

2025-11-09

How to correctly display the independent content of each site on the front page of the multi-site management function of AnqiCMS?

In today's digital environment, many businesses and individuals need to manage multiple websites, whether it be different brand sites, product sub-sites, or multilingual versions for different markets.A system that can efficiently handle content across multiple sites is particularly important to meet such demands.The multi-site management feature of AnqiCMS is exactly for this purpose, it allows you to easily manage multiple websites from a single backend, while ensuring that each site can independently and correctly display its exclusive content on the front page.### The core advantages of AnqiCMS multi-site management First, let's understand

2025-11-09

How to display friendly information to users on the front end during the website maintenance period of AnqiCMS's 'Shutdown Prompt' feature?

In website operations, we all understand the importance of maintenance work.Whether it is system upgrade, data migration, or solving emergency faults, the website will always have a period of time when it has to be "offline".However, how to ensure the smooth progress of maintenance work during this special period, while minimizing the impact on user experience and not damaging the professional image of the website, this is indeed a problem worthy of deep thought.The "Shut Down Prompt" feature of AnQiCMS (AnQiCMS) is specifically designed to address this pain point, allowing us to communicate information to the front desk users in a friendly and clear manner

2025-11-09