How to use the `block` tag under the `if` condition to decide whether to override the parent template content when inheriting (`extends`) a template?

Calendar 👁️ 62

Advanced Anqi CMS Template: Smart UsageextendswithblockAchieve conditional content coverage

In the daily operation of website management, we fully understand the importance of the maintainability and flexibility of website content for efficient operation.AnQi CMS provides a solid foundation for content management with its efficient architecture based on the Go language and a Django-like template engine syntax.where, template inheritance(extends) and content block (blockIt is the core of building reusable and scalable website layouts. But it is not enough to simply inherit and overwrite; often, we want child templates to 'intelligently' decide whether to override the content of the parent template under certain conditions, or to continue using the default design of the parent template.Today, let's delve into this clever and practical skill.

Template Inheritance: The Foundation for Building a Website Skeleton

Imagine, we are building a brand new corporate website template for AnQiCMS.A website usually has a fixed header, navigation, sidebar, and footer area, with only the core content area changing from page to page. At this time,extendsandblockThe combination is like the steel and concrete framework of building a house.

Firstly, we create a general parent template, for example named.base.htmlIn this parent template, we will define the overall structure and common elements of the website, and useblockThe label encloses the areas that allow child templates to be modified or filled in. These blocks are like reserved slots, waiting for specific content to fill them. For example:

<!-- base.html (父模板示例) -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{% block page_title %}AnQiCMS企业官网 - 领先的内容管理系统{% endblock %}</title>
    <meta name="description" content="{% block page_description %}AnQiCMS致力于提供高效、可定制的企业级内容管理解决方案。{% endblock %}">
    <!-- 引入通用样式、脚本等 -->
</head>
<body>
    <header>
        <!-- 网站通用头部,包含Logo、主导航等 -->
        {% block header_nav %}{% navList navs %}...{% endnavList %}{% endblock %}
    </header>

    <div class="main-wrapper">
        <aside class="sidebar">
            {% block sidebar_content %}
                <!-- 父模板默认的侧边栏内容,如通用广告、最新文章列表等 -->
                <p>这里是默认侧边栏,展示最新动态。</p>
            {% endblock %}
        </aside>
        <main class="content">
            {% block main_content %}
                <!-- 父模板默认的主内容区域提示 -->
                <p>欢迎来到AnQiCMS网站!</p>
            {% endblock %}
        </main>
    </div>

    <footer>
        <!-- 网站通用底部,包含版权信息、友情链接等 -->
        {% block footer_info %}{% system with name="SiteCopyright" %}{% endblock %}
    </footer>
</body>
</html>

Later, when we create specific pages, such as the detail page of an articlearticle_detail.htmlwe just need to{% extends 'base.html' %}inherit the parent template and then selectively rewrite some of theblockBlock, fill in the article's own title, content and other information. In this way, the overall layout of the website can be maintained consistently, and the personalized content of each page can be easily realized.

The beauty of dynamics: inblockis usedifConditions determine the retention of content

Now, we are facing a more refined requirement: some pages have unique sidebar content, while most other pages follow the common sidebar of the parent template. If we simply rewritesidebar_contentIf the block is removed, then these pages will completely lose the default sidebar provided by the parent template.We truly want something like a 'conditional overlay' - showing customized content of the sub-template when certain conditions are met;Otherwise, it will 'return' the default content of the parent template.

This isifThe tag is inblockThe place where the great show is. The Anqi CMS template engine supportsblockNested logical judgment inside. The key is that we can use{{ block.super }}This special variable to refer to the current context in the parent templateblockThe original content.

Let us take the sidebar as an example, assuming we have a special "Promotion Page", the sidebar needs to display a unique promotion advertisement instead of the regular latest news. Inspecial_promotion.htmlIn this sub-template, we can handle it like this:

<!-- special_promotion.html (子模板示例) -->
{% extends 'base.html' %}

{% set is_promotion_page = true %} {# 假设通过某种逻辑(如URL参数、文章标签、分类ID等)判断出这是促销页 #}

{% block page_title %}限时促销!不容错过 - {% tdk with name="Title" siteName=true %}{% endblock %}

{% block main_content %}
    <section class="promotion-banner">
        <img src="{% system with name='TemplateUrl' %}/images/promotion-banner.jpg" alt="年度大促">
        <h2>激动人心的促销活动标题!</h2>
        <p>这里是促销活动的详细介绍和规则。</p>
    </section>
    <article>
        <!-- 促销活动主体内容 -->
    </article>
{% endblock %}

{% block sidebar_content %}
    {% if is_promotion_page %}
        <div class="promotion-ad">
            <h3>仅限今日!</h3>
            <p>超值优惠,立即抢购!</p>
            <a href="/promo-details.html" class="btn btn-primary">了解详情</a>
        </div>
    {% else %}
        {# 如果is_promotion_page为false(例如,这个变量未设置或设为false),则渲染父模板的默认侧边栏内容 #}
        {{ block.super }}
    {% endif %}
{% endblock %}

In this example:

  1. We first pass through{% set is_promotion_page = true %}For example, in practice, this is usually determined dynamically based on backend data, such as{% if archive.Flag contains 'promo' %}or{% if category.Id == 123 %}) Set a conditional variable.
  2. Insidebar_contentInside the block, we use{% if is_promotion_page %}to judge.
  3. If the condition is true, the sub-template will render the promotional advertisement defined inside it.
  4. If the condition is false,{% else %}in the branch,{{ block.super }}will be executed, magically transferring the parent templatebase.htmlinsidebar_content

Related articles

The AnQi CMS template development tool: gracefully handle missing files using the `if_exists` parameter of the `include` tag

As an experienced website operations expert, I know how important efficiency and stability are in building and managing corporate websites.AnQiCMS (AnQiCMS) boasts its high-performance architecture based on the Go language and a flexible template system, providing us with powerful content management capabilities.In daily template development, the `include` tag is undoubtedly our powerful assistant for achieving modularization and improving code reusability.However, convenience also hides a small trap: if the template file referenced by `include` is unfortunately missing, the website page will immediately throw an error, affecting user experience

2025-11-06

How to load different layouts in AnQiCMS templates based on the current template type (such as `template_type`)?

In the practice of AnQiCMS (AnQiCMS), flexible template management is a key link in the efficient operation of the website.As an experienced website operations expert, I am well aware of how to load the appropriate layout for different scenarios, which not only optimizes user experience but also enhances the website's response speed and maintenance efficiency.Today, let's delve deeply into how to cleverly load different layout strategies in the AnQiCMS template, such as `template_type`.

2025-11-06

How does the `filter-yesno` filter help AnQiCMS templates handle the tri-state logic of 'yes/no/unknown'?

As an experienced website operations expert, I know that how to present data status efficiently and clearly in a content management system is one of the keys to successful operations.AnQiCMS (AnQiCMS) provides an excellent solution in this aspect with its flexible template engine and rich built-in filters.Today, let's delve into a seemingly simple yet powerful filter——`filter-yesno`, and how it helps AnQiCMS templates handle complex ternary logic such as 'yes/no/unknown'.

2025-11-06

What is the difference in handling variable null values between `filter-default` and `filter-default_if_none` in `if` condition judgments?

AnQiCMS (AnQiCMS) is a powerful assistant for our daily content operation, with its flexible template engine syntax making content display diverse and efficient.However, in practice, we often encounter situations where variable values are empty, such as when the article title is not filled in, or when a custom field has no data.How elegantly to handle these 'null' values to ensure that the website front-end display is always professional and friendly has become a topic that content operators must face.

2025-11-06

How to determine whether a user is logged in or has specific permissions to display private content in AnQiCMS templates?

As an experienced website operation expert, I fully understand the importance of realizing fine-grained content display in a content management system.Especially for systems like AnQiCMS that focus on enterprise-level applications and user experience, dynamically presenting content based on the user's login status or their permission group is a core strategy to enhance website personalization, achieve content monetization, and even build a membership system.Today, let's delve into how to skillfully utilize the powerful functions of the AnQiCMS template to achieve this goal

2025-11-06

How to determine whether the current page is the homepage, category page, detail page, or single page, and load the corresponding SEO information?

As an experienced website operations expert, I am well aware of the importance of Search Engine Optimization (SEO) in the increasingly fierce online environment.To do SEO well, the primary task is to ensure that every page of the website provides clear and accurate metadata to search engines.How can one determine the current page type (home page, category page, detail page, single page, etc.) and load the corresponding SEO information, which is a core issue often encountered by many operators and developers.Today, let's delve into the intelligent design and practical strategies of AnQiCMS (AnQiCMS) in this aspect

2025-11-06

How to display the image gallery based on whether there is an album in the `Images` field of `archiveDetail` or `pageDetail`?

## How to cleverly use Anqi CMS: intelligently judge and display image galleries in articles/pages As a senior website operation expert, I deeply understand the importance of content display for user experience and website attractiveness.In AnQiCMS (AnQiCMS) such an efficient and customizable content management system, how to flexibly present image content, especially dynamically displaying the image gallery based on whether there is an album, is a focus for many operators.

2025-11-06

How to determine whether a site has multilingual versions and display a language switch button using the `tag-languages` multilingual site tag?

AnQi CMS, as a Go language system deeply rooted in the field of enterprise-level content management, its powerful multilingual support is undoubtedly one of the core advantages to help enterprises expand into the global market.How can we intelligently determine whether a website is configured with multiple language versions and elegantly display language switch buttons when building websites for global users, which is a common problem encountered by content operation experts in template design.Today, let's delve into the `tag-languages` tag of Anqi CMS together, uncovering the mysteries of language switching.###

2025-11-06