As an experienced website operations expert, I know how important modularization and reusability are in building and maintaining a website.English CMS (EnglishCMS) relies on its efficient architecture based on Go language and Django-like template engine, providing great flexibility for content display.includeTags are one of the core functions that enable template reuse.However, powerful tools also need to be used carefully, otherwise they may bring unexpected 'surprises' to the website - such as page errors caused by the non-existent template files.

Today, let's delve into the use of the Anqi CMS,includeHow to elegantly ensure that the template file is introduced when labeling, thus avoiding page errors and keeping your website running smoothly.

includeThe charm and potential risks of tags

In the template design of AnQi CMS,includeLabels play a crucial role.It allows us to extract common page elements, such as headers, footers, sidebars, or any reusable code snippets, into independent template files.This way, we do not need to rewrite the same code on each page, which not only improves development efficiency but also makes the template structure clearer and easier to maintain.

For example, in yourindex.htmlIn the main template, you might do it like this to introduce common headers and footers:

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

<div class="main-content">
    <!-- 页面核心内容 -->
</div>

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

This approach is indeed efficient, but it also hides a potential risk: if someincludetemplate file, for examplepartial/header.html

Elegant solution:if_existsModifiers

Fortunately, the template engine of AnQi CMS (Pongo2, compatible with Django syntax) providesincludeA very practical modifier for tags -if_exists. The addition of this modifier completely solves the problem of files that may not exist when importing.

When you areincludeadded after theif_existsWhen, Aiqi CMS will first check if the template file exists when trying to load the file.

  • If the file existsit will be introduced and rendered as usual.
  • If the file does not existit will silently skip thisincludeOperation will not result in any errors and will not affect the normal rendering of the other parts of the page.

This is like giving you aincludeThe operation has added a layer of intelligent protection, so even if there is a file loss, the website can still run normally, just missing the content of the skipped module.

Useif_existsThe syntax of the modifier is very simple, onlyincludeadd the template path of theif_existsas follows:

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

Now, evenpartial/header.htmlthe page will not crash if the file does not exist.

Actual application scenarios and **practice

if_existsModifiers are very useful in many scenarios, especially when dealing with optional, conditionally dynamic, or user-defined template fragments:

  1. Optional page moduleFor example, a certain sidebar ad slot on a website, a custom module created by the user, or a notification bar that is only displayed during specific events.These module templates may not always exist, or may not be required to be displayed on some pages.

    {# 引入一个可能存在的广告组件,如果文件不存在则不显示 #}
    {% include "widgets/ad_banner.html" if_exists %}
    
  2. User-defined template fileIf your website allows advanced users to upload or specify custom template files (such as custom article detail page layouts), then when including these user-specified templates, useif_existsIt can ensure that the website will not crash as a whole even if the user uploads a wrong filename or the file is deleted.

  3. Development and test environment: In the development process, you may still be building a module, and the template file is not yet complete. Useif_existsto avoid being hindered by these incompleteincludeand disrupting the debugging of other parts.

Combine variable passing (with) and scope control (only)

includeThe power of labels also lies in the ability to pass variables and control scope.if_existsCan be well combined with these features.

  • withPass variablesWhen you introduce a template that requires some specific data, you can usewithkeyword to pass variables.
    
    {# 引入侧边栏,并传递当前文章的ID和相关分类数据 #}
    {% include "partial/sidebar.html" if_exists with currentPostId=archive.Id categories=categoryList %}
    
  • onlyScope limitationIf you want the template to use only the variables you explicitly pass, and not inherit all the context variables from the parent template, you can useonlyThis helps avoid variable name conflicts and improve the independence of modules.
    
    {# 引入一个简单的版权信息模块,只传递年份变量,不暴露其他复杂数据 #}
    {% include "common/copyright.html" if_exists with currentYear=nowYear only %}
    

Complete example: Building a robust page structure

Let's take a look at a combinationif_exists/withandonlyThe page structure example, showing how to build a flexible and robust template:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{% tdk with name="Title" siteName=true %}</title>
    <meta name="keywords" content="{% tdk with name="Keywords" %}">
    <meta name="description" content="{% tdk with name="Description" %}">
    <link rel="stylesheet" href="{% system with name="TemplateUrl" %}/css/main.css">
    {# 如果有自定义的头部样式,尝试引入,不存在也不会报错 #}
    {% include "custom/head_styles.html" if_exists %}
</head>
<body>
    {# 页面头部,无论如何都应尝试引入,但避免致命错误 #}
    {% include "partial/header.html" if_exists with siteName=system.SiteName %}

    <div class="container">
        <div class="main-content">
            <!-- 核心内容区域,例如文章详情 -->
            {% if archive %} {# 确保是文章详情页 #}
                <article>
                    <h1>{{ archive.Title }}</h1>
                    <div class="article-meta">
                        <span>发布于 {{ stampToDate(archive.CreatedTime, "2006-01-02") }}</span>
                        <span>浏览量:{{ archive.Views }}</span>
                    </div>
                    <div class="article-body">
                        {{ archive.Content|safe }}
                    </div>
                    {# 相关文章模块,可能是可选的,或只有在有数据时才显示 #}
                    {% include "modules/related_articles.html" if_exists with currentArchiveId=archive.Id only %}
                </article>
            {% else %}
                {# 非文章详情页或内容不存在时的备用显示 #}
                <p>内容加载失败或页面不存在。</p>
            {% endif %}
        </div>

        <aside class="sidebar">
            {# 侧边栏的通用组件,即使文件不存在也不影响主内容 #}
            {% include "partial/sidebar_categories.html" if_exists %}
            {% include "partial/sidebar_hot_posts.html" if_exists %}
        </aside>
    </div>

    {# 页面底部,同样采用 if_exists 确保网站稳定性 #}
    {% include "partial/footer.html" if_exists with copyright=system.SiteCopyright %}

    <script src="{% system with name="TemplateUrl" %}/js/main.js"></script>
    {# 引入自定义的JS,如果文件不存在则跳过 #}
    {% include "custom/body_scripts.html" if_exists %}
</body>
</html>

Summary

In the template development of Anqi CMS,includeTag combinationif_existsModifier, provides a powerful and safe way to build modular templates.It not only ensures the stability of the website and avoids page errors due to missing files, but also enhances the flexibility and maintainability of template design.Reasonably utilizing this feature will enable your CMS website to demonstrate excellent robustness and user experience in the face of various operational challenges.


Common Questions (FAQ)

Q1:if_existsand inincludeUsed outside{% if ... %}What's the difference in checking if a file exists?

A1: if_existsYesincludeThe modifier built into the tag, which is trying to load a filepreviouslyPerform existence check. If the file does not exist,includethe operation will be skipped directly, without any errors or logs