How to determine if a variable (such as the article title) exists or is empty in a template and display a custom default value?

Calendar 👁️ 72

In website content management, ensuring the completeness and user experience is crucial.Sometimes, due to missing content or unassigned variables, blank areas or error messages may appear on web pages, which undoubtedly affects the professionalism of the website.The AnQiCMS template engine provides a flexible and powerful mechanism to help users elegantly handle these situations, ensuring the robust presentation of page content even if variables do not exist or are empty.

In AnQiCMS template design, we often encounter situations where we need to display a variable (such as article title, description, image URL, etc.).However, in practice, these variables may be missing for various reasons.This is when we need a method to determine their existence and provide a custom default value if necessary, to avoid the page looking empty or showing errors.

The basic approach to variable existence and null value judgment

AnQiCMS template engine adopts syntax similar to Django, which means we can make use ofifTags for conditional judgment. This is the most direct method to handle the existence or null value of a variable.

When we want to judge whether a variable (such asarchive.Title, i.e., the article title) has a value, we can use it directly.{% if 变量名 %}Such a structure. This judgment method checks whether the variable is a non-empty string, non-zero number, nonnil(Null Pointer) Object or non-empty collection. If the variable has actual content, the condition is true; otherwise, it is false.

For example, if you want to display a default prompt when the article title is empty:

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

If you need to accurately determine whether a variable is an empty string, rather than simply "no value", you can explicitly compare it with an empty string:

{% if archive.Title == "" %}
    <h1>内容正在编辑中...</h1>
{% else %}
    <h1>{{ archive.Title }}</h1>
{% endif %}

Use a filter to elegantly set the default value

AlthoughifJudgment can solve the problem, but in some cases, Anqi CMS provides a more concise and elegant way to handle default variable values - that is to use filters. Among them,defaultanddefault_if_noneThese filters are the tools to meet this requirement.

defaultFilters are very practical. When a variable isnilWhen it is null pointer, empty string, or certain types of zero values (such as the number 0), it will output the default value you provided. This means you do not need to explicitly writeif-elseStructure, which can set a default content for possibly empty variables.

For example, set a default value for the article title:

<h1>{{ archive.Title|default:"未命名文章" }}</h1>

The meaning of this code is: ifarchive.TitleIf there is a value, display it; if not, display 'Unnamed Article'.

Another one isdefault_if_noneFilter. If you only need to targetnil(The case where a null pointer is set to a default value, but you want an empty string or zero value to be displayed, then)default_if_noneIt would be a more precise choice. In practice, since most content variables are stored as empty strings in the database if there is no value, thereforedefaultFilters are usually more general and commonly used.

For example, if you want to displayarchive.TitleWithnilthe default value but an empty string is also valid content:

<h1>{{ archive.Title|default_if_none:"标题信息缺失" }}</h1>

However, in the normal use of Anqi CMS, variables usually either have an explicit value or are empty strings,nilwhich is relatively rare, sodefaultThe filter is sufficient to handle the vast majority of scenarios.

Combined with specific scenarios: taking the article title as an example

Let's take an example of a common article detail page to see how to apply these skills in actual templates.Assuming we are designing an article detail template, we need to display the title, content, and thumbnail.

Firstly, obtaining the article detail data is usually througharchiveDetailLabel it and assign the result to a variable, for examplearticle:

{% archiveDetail article %}
    <div class="article-header">
        <h1>{{ article.Title|default:"【重要通知】本站最新动态" }}</h1>
        <p class="description">{{ article.Description|default:"本文暂无简介,敬请期待更多精彩内容!" }}</p>
    </div>

    <div class="article-image">
        <img src="{{ article.Thumb|default:"/static/images/default-thumbnail.webp" }}" alt="{{ article.Title|default:"默认图片" }}">
    </div>

    <div class="article-content">
        {% if article.Content %}
            {{ article.Content|safe }}
        {% else %}
            <p>文章内容正在创作中,请稍后访问。</p>
        {% endif %}
    </div>
{% endarchiveDetail %}

In this example:

  • Article titlearticle.TitleAnd descriptionarticle.DescriptionUsed directlydefaultFilter, when they are empty, they will display the specified default text.
  • Article thumbnailarticle.ThumbUsed similarlydefaultA filter that loads a preset default image when the image path is empty, preventing broken images from appearing on the page.
  • Article contentarticle.ContentDue to the possibility of containing complex HTML structures, here we useiftags to determine if they exist. If they exist, then through|safeThe filter outputs safely; if it does not exist, it displays a friendly prompt text.

By these methods, regardless of how the data in the backend content management system changes, our front-end page can maintain good display effects and provide users with a smooth and professional browsing experience.


Frequently Asked Questions (FAQ)

1. How to determine if a list (such as a related articles list) is empty, and display 'No content' when it is?Anqi CMS template engine'sforLoop tags are built-inemptyThe clause is specifically used to handle the case of an empty list. You do not need to use it extra.ifJudgment:

{% archiveList relatedArchives with type="related" limit="5" %}
    {% for item in relatedArchives %}
        <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
    {% empty %}
        <li>暂无相关内容。</li>
    {% endfor %}
{% endarchiveList %}

2. If a variable containing an image link (such asarchive.LogoIs it possible to avoid displaying a broken image and provide a default image in the template?The simplest method is to usedefaultfilter. InsrcApply the filter directly in the property, specify the path to a default image accordingly.

<img src="{{ archive.Logo|default:"/public/static/images/default_logo.png" }}" alt="{{ archive.Title|default:"网站Logo" }}">

Make sure/public/static/images/default_logo.pngIt is the actual default image path existing on your website.

3. Can I display a more complex HTML structure when the variable is empty?Of course, in this case, combineifTags andelseBlocks can be implemented. You can write any HTML code inelsea block, even a predefined template snippet.include.

{% if archive.CustomAdHtml %}
    <div class="custom-ad-area">
        {{ archive.CustomAdHtml|safe }}
    </div>
{% else %}
    <div class="default-ad-placeholder">
        <p>广告位招租中...</p>
        <a href="/contact-us">了解详情</a>
    </div>
{% endif %}

Related articles

How can AnQi CMS achieve automatic image compression and conversion to WebP format to optimize page loading performance?

Website images are important elements to enhance the attractiveness of content, but if not handled properly, they may also become the 'culprits' that slow down the website loading speed.For website operators, optimizing image loading performance can not only improve user experience but also have a positive impact on search engine rankings (SEO).AnQi CMS is an efficient content management system that fully considers this point, providing users with convenient and powerful image optimization features, especially automatic compression and WebP format conversion, allowing the website to maintain image quality while having faster loading speed.###

2025-11-08

How to display a dynamic banner image on the homepage of a website and implement click-through?

Displaying dynamic banner images with click-through functionality on the website homepage is a common need to enhance the visual appeal and user interaction of the site.By utilizing the powerful functions and flexible template mechanism of AnQiCMS, we can easily achieve this goal.The entire process is mainly divided into two parts: background configuration and front-end template invocation. ### First Step: Configure Banner Image and Link To display a dynamic rotating Banner on the website homepage, you first need to upload the image and set the link in the AnQiCMS backend. Typically

2025-11-08

How to format an article's publish timestamp into a user-friendly date and time format, such as '2023 January 01 14:30'?

User-friendly date and time display is crucial for website content.A clear and readable time format not only improves the visitor's reading experience, but also helps them quickly understand the publishing or updating timeliness of the content.In AnQiCMS, formatting the publication timestamp of articles into a format such as '2023-01-01 14:30' is both flexible and efficient.Understanding the use of timestamps in AnQiCMS In the content managed by AnQiCMS, whether it is articles, products, or other custom models

2025-11-08

How to receive and display custom form fields from the backend in a frontend comment form?

In website operation, the message form is an important channel for interacting with users, collecting feedback and leads.AnQiCMS provides flexible comment functions, one very practical ability is to allow us to customize form fields in the background, and seamlessly present them in the front-end comment form to meet the personalized information collection needs of different business scenarios.Next, we will discuss in detail how to implement this feature in Anqi CMS.### One, define the custom message field in the background First, we need to enter the Anqi CMS backend management interface

2025-11-08

How to implement complex conditional judgment and content iteration display in templates using `if/else` and `for` loop tags?

AnQi CMS as an efficient and flexible content management system, its template design capability is the key to building a rich and varied website content.During the template creation process, flexibly using conditional judgment (`if/else`) and content iteration (`for` loop`) tags can help us achieve a more intelligent and dynamic content display, allowing the web page to present personalized layouts and information according to different situations.

2025-11-08

How to truncate a long text content while displaying and automatically add an ellipsis?

In website operation, we often need to display various text content on the page, such as the abstract of article lists, the preview of product introductions, or a brief description of a detailed page.Faced with long-form content, how can one elegantly present the core information within limited space, and guide users to click for more details, is a common need.It is particularly important to truncate long text content and automatically add an ellipsis.AnQiCMS (AnQiCMS) is an efficient and flexible content management system that fully considers this user demand

2025-11-08

In the display of the `Content` field of the article, how can I manually control the rendering conversion from Markdown to HTML?

When managing website content in AnQi CMS, we often use Markdown's concise and efficient features to write articles.However, ensuring that this Markdown-formatted content is rendered correctly into attractive HTML on the front-end page can sometimes be a focus for operators.This article will delve into how Anqi CMS handles the Markdown content of the `Content` field of the article, and guide you on how to manually control this rendering conversion process in the template.

2025-11-08

How to retrieve and display the list of all related documents under the Tag detail page?

In content operation, tags (Tag) are an extremely important tool that can help us effectively organize content, improve the quality of internal links on the website, and ultimately improve the user's browsing experience and the search engine's crawling efficiency.By tagging articles, products, or other content with relevant tags, we can associate content with the same theme scattered across different categories, forming a closer knowledge network.

2025-11-08