How to determine if a variable is empty in AnQiCMS template and display default content?

Calendar 👁️ 70

In website content operation, the integrity of data and the elegance of display are crucial.We often encounter such situations: some fields of data may be missing for various reasons, such as an article may not have an illustration, a product may not have a detailed description, or a custom field may not be filled in.If the template code does not make the corresponding null value judgment, it may cause the page to appear blank, affecting aesthetics, or even trigger template rendering errors, affecting user experience.

AnQiCMS with its efficient architecture based on the Go language and flexible design similar to the Django template engine, provides us with various powerful and intuitive ways to determine if a variable in the template is empty and display default content accordingly, allowing the website to maintain a good user experience even when data is incomplete.Let's explore these practical skills together.

Most intuitive and powerful: {% if ... %}logical judgment tag

In the AnQiCMS template,ifTags are the core tools we use for conditional judgment. They can determine whether a variable is 'true' or 'false'. A variable is considered a 'false' value when it is an empty string""numbers0and a boolean valuefalseand in Go languagenilequivalent to other languagesnullorNone)ifthe statement will execute itselseBlock content.

Basic usage:

Assume you have an article objectarchiveincludingTitle(Title) andDescription(description) etc. You can judge it like thisTitlewhether it is empty:

{% if archive.Title %}
    <h1>{{ archive.Title }}</h1>
{% else %}
    <h1>暂无标题</h1>
{% endif %}

Ifarchive.TitleNot empty, the page will display the actual title; otherwise, it will display 'No title'. Similarly, you can also useif notto determine if a variable is empty:

{% if not archive.Description %}
    <p>该文章暂无详细描述。</p>
{% else %}
    <p>{{ archive.Description }}</p>
{% endif %}

This method is suitable for scenarios where you need to display the entire HTML block or perform more complex logic.

Shortcut:defaultFilter

When you only need to provide a default value in the output, without the need for complex logical judgment structures,defaultThe filter is your **choice. It is concise and efficient, making the code more readable.

defaultThe filter will be applied when a variable is evaluated as a 'falsy' value (including an empty string""numbers0and a boolean valuefalseas well asnil),display the default content you provided.

Usage example:

<p>作者:{{ archive.Author|default:"佚名" }}</p>
<img src="{{ archive.Logo|default:'/static/images/default_logo.png' }}" alt="{{ archive.Title|default:'文章图片' }}" />
<p>价格:{{ product.Price|default:0 }} 元</p>

In the above example:

  • Ifarchive.AuthorEmpty, 'Anonymous' will be displayed.
  • Ifarchive.LogoEmpty (or invalid), 'Unknown' will be displayed./static/images/default_logo.pngAs the default image.
  • Ifproduct.PriceEmpty or0It will display0yuan.

defaultThe filter is very suitable for inline output, it can effectively avoid blank or broken links appearing on the page.

For the list:{% for ... %}Combine{% empty %}

When processing list data, especially when it is necessary to judge whether the list is empty and display a prompt message,forrepeatedlyemptyThe block is very practical. It provides an elegant way to handle the case where the list is empty, avoiding redundancy.ifjudgment.

Usage example:

Assuming you want to display a list of related documents, but sometimes it may not find related content:

{% archiveList relatedArchives with type="related" limit="5" %}
    {% for item in relatedArchives %}
        <div class="related-item">
            <a href="{{ item.Link }}">{{ item.Title }}</a>
        </div>
    {% empty %}
        <div class="no-related-content">暂无相关文档。</div>
    {% endfor %}
{% endarchiveList %}

IfrelatedArchivesThe list is empty or does not exist,emptyThe content within the block will be rendered, prompting the user that there is no relevant content, rather than leaving an empty area.

More accurate judgment:default_if_noneFilter

In certain specific scenarios, you may need to distinguish between a variable that does not exist at allnilor is merely empty (such as an empty string)""numbers0. In this casedefault_if_noneThe filter comes into play.

default_if_nonethe filter will only be applied if the variable's value isnilWhen it displays default content. This means it will not affect an empty string""or numbers0Take effect.

Usage example:

Assuming there is a custom fieldproduct.SpecificationIt may benil(Not set), or may also be""(Set but content is empty).

<p>产品规格(default):{{ product.Specification|default:"未填写" }}</p>
<p>产品规格(default_if_none):{{ product.Specification|default_if_none:"未设置" }}</p>
  • Ifproduct.SpecificationIsnil:
    • The first line will display "Not filled in."
    • The second line will display "Not set."
  • Ifproduct.SpecificationIs""(Empty string):
    • The first line will display "Not filled in."
    • The second line will display an empty string (i.e., no content will be displayed).

This filter is very useful when it is necessary to strictly differentiate between "unassigned" and "assigned but empty" scenarios.

Combining practical **practice

  • Images and links:For imagessrcProperties and linkshrefProperties, usedefaultThe filter provides an alternative image or link to prevent the appearance of a 'broken link' icon or inaccessible links.
  • Rich text content:For article details, product descriptions, and other rich text content, it is usually better to hide the area directly or display a "No content" prompt when the content is empty, at this time{% if ... %}CombinesafeThe filter (used for safely rendering HTML content) would be a better choice:
    
    {% if archive.Content %}
        <div class="article-content">{{ archive.Content|safe }}</div>
    {% else %}
        <div class="article-content">暂无详细内容。</div>
    {% endif %}
    
  • Custom field:AnQiCMS is a powerful content model that allows us to create various custom fields. When calling these fields in the template, it is also necessary to make proper null value judgments.
    
    {% archiveDetail author with name="author" %}
    {% if author %}
        <p>作者:{{ author }}</p>
    {% else %}
        <p>作者信息待补充。</p>
    {% endif %}
    

By flexibly using these methods to judge whether variables are empty, you can write more robust and better user experience code.

Related articles

How to display a custom page template independently on a specific page (such as About Us)?

Hello! When using AnQi CMS to build a website, we often encounter such needs: some specific pages, such as 'About Us', 'Contact Us', or some special topic pages, need to have a completely different layout and design from other pages on the website.Luckyly, AnQi CMS provides a very flexible solution for this, allowing you to easily specify independent custom templates for these pages.AnQi CMS with its efficient features based on the Go language and support for Django template engine syntax, brings great convenience and customizability to content display

2025-11-07

How to get and display the Tag list of articles in the front-end template of AnQiCMS?

AnQiCMS as an efficient and flexible content management system, provides a wealth of features to help operators manage and display website content.Among them, the Tag tag function of the article is an important factor for optimizing content organization, improving user experience and SEO effects.Understand how to obtain and display these tags in front-end templates, which is crucial for building a website with comprehensive functions.### In AnQiCMS backend management tags Before delving into the front-end template, let's briefly review how tags work in the AnQiCMS backend

2025-11-07

How to implement keyword search and filtering display on article list or search result pages?

How to allow visitors to quickly find the content they need among the vast amount of information on our website is undoubtedly the key to improving user experience and the effectiveness of content marketing.AnQiCMS (AnQiCMS) knows this and therefore provides a powerful and flexible mechanism to help us easily implement keyword search and content filtering functions on article lists or search result pages.The implementation of this feature mainly revolves around the core template tags of AnQi CMS, allowing us to transform the content of the background management into a user-friendly interactive interface through the exquisite design of the frontend template.###

2025-11-07

How to add watermarks to images on the AnQiCMS website to protect original content?

In today's increasingly rich digital content, protecting the copyright of original works is particularly important, especially for visual content such as images.When your website publishes a large number of carefully crafted images, if they are not protected, it is easy for others to copy and repost them arbitrarily, which not only infringes on your labor results but also weakens the uniqueness of the content.Adding a watermark to an image is a simple and effective means of copyright protection, which can clearly assert ownership of the content without affecting the beauty of the image, effectively deterring unauthorized use.Anqi CMS as a highly efficient

2025-11-07

How to implement safe output of HTML tags in article content to avoid XSS attacks?

In AnQiCMS, we not only pursue efficient and flexible content management, but also regard website security as a core element.In daily content creation and template development, a seemingly simple HTML tag output actually hides potential security risks, the most common of which is cross-site scripting (XSS) attack.Understanding how AnQiCMS processes HTML output and mastering security practices is crucial for building a robust and reliable website.How does AnQiCMS handle HTML content output?In AnQiCMS template rendering mechanism

2025-11-07

How to extract the article summary and add an ellipsis in AnQiCMS template?

In website operation, how to make the article list page both beautiful and informative is a common concern.Generally, we do not display the full content of the article on the list page, but instead use a short 'abstract' to attract readers to click.To maintain the cleanliness and professionalism of the page, these summaries often need to be automatically truncated when exceeding a certain length and appended with an elegant ellipsis.AnQiCMS is a powerful content management system that provides flexible tools in the template to help us meet this need.Below, we will discuss in detail how to use AnQiCMS

2025-11-07

How to display a list of website friend links in the front-end template?

In website operation, friendship links are not only a bridge between websites, but also an important strategy to enhance website authority, increase external traffic, and optimize search engine rankings.Reasonably configure and display friendship links, which can effectively improve the website's SEO performance and provide users with more valuable external resources.AnQiCMS as an efficient content management system, fully considers this need, and provides a simple and intuitive way to manage and display friend links in the front-end template.### Backend Management: Setting and Maintaining Friend Links Display Friend Links on the Front-end Page

2025-11-07

How to display a user comment list on the front end and support review status display?

User comments are an important manifestation of website vitality, they not only enhance the interactivity of content but also provide valuable reference for other visitors.AnQi CMS understands the importance of comment management, providing simple and powerful features that allow you to flexibly display comment lists on the website front end and clearly identify the review status of comments.The core of displaying the comment list on the front-end: `commentList` tag To display user comments on your website's front-end page, you need to use the `commentList` template tag provided by AnQiCMS

2025-11-07