How to reuse common code snippets through the `include` tag in AnQiCMS templates to optimize the display structure?

Calendar 👁️ 71

When building and managing websites, improving efficiency and maintaining code cleanliness is a goal pursued by every operator. AnQiCMS, as an efficient content management system, provides powerful template functions, among whichincludeTags are the tools to achieve this goal. They allow us to abstract out repeated code snippets on the website, form independent modules, and then reference them where needed, greatly optimizing the template structure and subsequent maintenance work.

UnderstandingincludeTag: The foundation of modular websites

Imagine that your website has many pages, but each page shares the same header, footer, and sidebar.If there is no modular mechanism, you may need to rewrite this content on each page template.Once you need to modify a small detail of the page header, such as adding a navigation link, you will have to make changes on all related pages, which is not only time-consuming but also prone to errors.

includeTags are born to solve this pain point. In the Anqi CMS template system,includeThe label is like taking a large Lego set apart into individual pieces.These small parts (such as headers, footers, sidebars, and specific feature blocks, etc.) can be made separately and then assembled anywhere as needed.The AnQi CMS supports syntax similar to the Django template engine, making modularization simple and intuitive.

Why chooseincludeTags? Three core advantages

UseincludeTags are not just a convenience at the code level; they have profound benefits for the overall operation and management of the website:

  1. Significantly improve code reusability:This isincludeThe most direct benefit. By encapsulating common modules (such as website header navigation, footer copyright information, and unified display styles for article list items) into independent template files, you do not need to write the same code repeatedly on multiple pages.This means that the development workload is greatly reduced, avoiding unnecessary repetitive labor.

  2. Optimize template structure, improve readability:When a page's template file becomes long and complex, it becomes very difficult to find and understand the code of a specific functional area. ThroughincludeYou can decompose a complex page into small files with clear logic and single responsibilities. For example,index.htmlit may only contain references toheader.html/sidebar.html/main-content.htmlandfooter.html, making the overall structure clear at a glance.

  3. Simplify website maintenance, reduce error rates:Website content and features often need to be updated. If the code of a common module is scattered across multiple template files, any modification requires individual operations, increasing the maintenance cost and the risk of introducing errors. And usingincludeAfter, you only need to modify a contained file, and all pages referencing it will be automatically updated, greatly simplifying the maintenance process and ensuring consistency of modifications.

How to use it in Anqi CMS templateincludeTag?

The Anqi CMS template files usually use.htmlas the suffix, and store them uniformly in/templatethe directory. For theincludecommon code snippets, it is recommended to place them in/templateUnder the directorypartial/In a subdirectory, for examplepartial/header.html/partial/footer.htmletc., which is a good organizational habit.

Basic Introduction Method

The simplestincludeThe usage is to directly specify the path of the template file to be imported:

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

Thus,header.htmlandfooter.htmlThe content will **be included into the corresponding position of the current template file.

Passing variables: making the included module more flexible

Sometimes, the public modules you introduce need to display different content based on the context of the current page.For example, a generic sidebar may need to know the current article's ID to display related articles.Now, you can usewithParameters are passed to the template variables introduced:

{# 在当前模板中 #}
{% include "partial/sidebar.html" with current_article_id=article.Id %}

Inpartial/sidebar.htmlIn the file, you can use it directly:current_article_idThis variable has been introduced:

{# partial/sidebar.html 文件中 #}
<div>
    {% if current_article_id %}
        <!-- 显示与文章 {{ current_article_id }} 相关的侧边内容 -->
    {% else %}
        <!-- 显示通用侧边内容 -->
    {% endif %}
</div>

If you need to pass multiple variables, just separate them with spaces:

{% include "partial/meta.html" with page_title="关于我们" page_keywords="公司,简介" %}

Limit the scope of variables: maintain clear boundaries

By default,includeThe template introduced can access all variables of the current template. But to avoid name conflicts or unnecessary coupling, you can useonlyThe parameter restricts the visibility of the variable to pass through onlywithExplicitly passing the variable:

{% include "partial/meta.html" with page_title="关于我们" only %}

In this case,partial/meta.htmlAccess will be restricted topage_titleThis variable, and cannot access any other variables in the current template.

Gracefully handle non-existent files:if_exists

If you are not sure whether a certainincludetemplate file exists, but you don't want the page to crash due to the file not existing, you can useif_existsparameter. This way, if the file does not exist, theincludeThe statement will be silently ignored without interrupting the page rendering:

{# 如果 partial/ads.html 存在则引入,否则忽略 #}
{% include "partial/ads.html" if_exists %}

Conclusion

includeTags are a basic and powerful tool in the development of Anqi CMS templates.By it, we can easily achieve the modularization and structuring of templates, effectively improve development efficiency, reduce maintenance costs, and ultimately provide website users with more stable and faster access experience.master and use wellincludeThe tag will make your website operation work twice as effectively.

Frequently Asked Questions (FAQ)

  1. includeTags andextendsWhat are the differences between tags? extendsTags are mainly used for template inheritance, it defines a basic layout (skeleton), and other templates can be based on this skeleton to fill or override specific content blocks (block)。WhileincludeTags are used to insert a small code snippet (such as a header or footer) into the specified location of any template file. In simple terms,extendsis 'I build based on you,'includeIs "I insert you here".

  2. Can I useincludeCan tags introduce modules that dynamically generate content?Of course you can.includeThe tag itself does not limit the dynamism of the content. As long as the template file being introduced can access the variables it needs (whether throughwithParameter passing, or inheriting through the default context), it can render dynamic content. For example, a sidebar module that displays the latest articles, as long as it finds the latest article list in the parent template and passes it toincludeThe sidebar template, and it can be displayed normally.

  3. includeWill the tag affect the loading speed of the website? includeThe tag itself is part of server-side rendering, which merges all included template files into a complete HTML file before sending the page to the user.Therefore, it will not increase the number of requests loaded by the client browser.On the contrary, since the template code is more modular and concise, maintenance and optimization are also easier, in the long run, this may even help improve development efficiency and performance.

Related articles

How to define and use variables in AnQiCMS templates to optimize the display and management of content?

In AnQi CMS, flexibly using template variables is the key to optimizing website content display and management efficiency.It not only makes your website content more dynamic, but also greatly improves the maintainability and reusability of the template.This article will delve into how to define and use variables in AnQiCMS templates, as well as how to better present content through these techniques. ### Variables: The Foundation of Living Content Imagine how cumbersome it would be if every title, every paragraph on a website had to be manually modified.The introduction of variables is to solve this pain point

2025-11-07

How to correctly format timestamps in AnQiCMS templates so that content is displayed as needed?

In the daily operation of website content, time information plays a vital role.No matter the publication date of the article, the launch time of the product, or the latest update of the content, these time points directly affect users' perception and trust in the information.However, in the templates of content management systems, we often encounter dates stored in the form of "timestamps", which are precise but not intuitive.How should we correctly format these timestamps in the AnQiCMS template so that the content can be displayed in the way we expect?

2025-11-07

How to use the (for) loop tag in AnQiCMS template to traverse and display the content list?

Efficiently using the `for` loop tag in AnQiCMS templates to display content lists is an indispensable core skill for building dynamic websites.By flexibly using the `for` loop, we can easily traverse various types of data collections and display them in a customized style on the website page, whether it is a news list, product display, category navigation, or any other repetitive content block, the `for` loop can help you a lot.

2025-11-07

How to use conditional judgment (if/else) tags to control the display logic of content in AnQiCMS templates?

In the development and maintenance of website templates, we often encounter the need to display or hide different content based on specific conditions.This dynamic content display logic is crucial for improving user experience, realizing personalized functions, and optimizing the website structure.AnQiCMS (AnQiCMS) is a powerful content management system that provides a flexible template engine, among which the condition judgment (`if/else`) tags are the core tools to achieve this goal.

2025-11-07

How to implement page layout inheritance and rewriting using the `extends` tag in AnQiCMS templates?

When building a website, maintaining the uniformity of the page style, improving development efficiency, and reducing maintenance costs is the goal pursued by every website operator.AnQiCMS (AnQiCMS) deeply understands this, and its template system design draws on the excellent ideas of the Django template engine, among which the `extends` tag is one of the core functions to achieve this goal. ### The Core Concept of Template Inheritance Imagine you are designing a series of posters.Each poster has a common brand logo, top title, and bottom contact information, with only the promotional content in the middle being different

2025-11-07

How to set the automatic compression and thumbnail processing method in AnQiCMS, which affects the image display on the front end?

The quality of website content is often not just reflected in text, but images as visual elements also play a crucial role.In website operation, how to efficiently handle images, ensuring that the images are clear and beautiful while also considering the loading speed, this is the core value of AnQiCMS image processing function.Today, let's delve deeper into how AnQiCMS helps us manage the automatic compression and thumbnail processing of large images, as well as how these settings will affect the display effect of images on the website's frontend.### Say goodbye to slow image loading

2025-11-07

How to configure the category template and document template in the background of AnQiCMS to achieve personalized content display?

As website operators, we all hope that our website content can be presented to visitors in the most attractive way possible.This is not just about visual beauty, but also about how the content structure can better serve users and how to highlight the unique brand character of the website.AnQiCMS fully understands this need, therefore it provides a powerful and flexible template configuration feature in the background, allowing you to achieve highly personalized displays based on different content types - whether it is articles, products, or category pages.Below, let's learn together how to configure category templates and document templates in the AnQiCMS backend

2025-11-07

How to configure banner images and thumbnails for a single page in AnQiCMS to enrich its visual display?

Today, with the increasing richness of website content, relying solely on text to convey information is no longer enough.Visual elements, such as eye-catching banner images and expressive thumbnails, can attract visitors' attention at first glance and enhance the professionalism and user experience of the website.For AnQiCMS users, cleverly configuring these visual elements for single pages (such as "About Us", "Contact Us", or "Service Introduction", etc.) is a simple operation that can bring great benefits.AnQiCMS fully understands the importance of content display and provides an intuitive backend management interface and a flexible template calling mechanism

2025-11-07