How to determine if a variable exists or is empty in a template and display different default content based on the result?

Calendar 👁️ 71

During the development and maintenance of website templates, we often encounter situations where variables may not exist, are empty, or do not meet expectations.If these variables are not processed properly, it may cause the page to display abnormally, or even trigger errors, affecting the user experience.AnQiCMS provides a powerful and flexible template engine based on Django syntax, allowing us to easily determine the state of variables and display different content accordingly.

It is crucial to ensure the robustness and user experience of the website, mastering how to judge whether a variable exists or is empty in templates, and provide friendly default content.This can not only avoid 'blank pages' or 'error messages', but also keep the website with good display effects when the data is incomplete.

UtilizeifThe statement performs conditional judgment

The most basic and most commonly used method is to make use ofifConditional judgment statements. The Anqi CMS template engine will handlenilan empty string""an empty listfalsenumbers0Values are automatically considered "falsey". This means you can directly use{% if variable %}to determine if a variable has实质性 content.

For example, when we want to display the title of an article, if the article title does not exist or is empty, we can provide a default placeholder:

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

Here, archive.TitleIf it exists and is not empty, its content will be displayed; otherwise, the page will display "No title content".

We can also make a reverse judgment, check if the variable is 'not existent' or 'empty':

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

When you need to check for more specific null value types, such as whether a string is indeed an empty string, you can use== ""exact matching, or combinelengthfilter.

{% if article.Content == "" %}
    <p>内容正在完善中,敬请期待!</p>
{% else %}
    <p>{{ article.Content|safe }}</p>
{% endif %}

multiple condition judgments as wellelifandelseKeywords, make the logic clearer:

{% if user.isVip %}
    <p>尊贵的VIP用户,欢迎您!</p>
{% elif user.isLoggedIn %}
    <p>您好,普通会员。</p>
{% else %}
    <p>访客您好,请登录享受更多服务。</p>
{% endif %}

Elegant handling of collection data:for ... empty ... endfor

When displaying list data, such as article lists, product lists, or image galleries, we often need to determine if the collection is empty.If empty, display 'No data available' or similar prompts.for ... empty ... endfor.

When you usearchiveListorcategoryListSuch tags to get list data, if the returned collection is empty,emptyThe content inside the block will be executed, avoiding extraifnested statement judgments:

{% archiveList archives with type="list" categoryId="1" limit="10" %}
    {% for item in archives %}
    <li>
        <a href="{{ item.Link }}">{{ item.Title }}</a>
        <p>{{ item.Description }}</p>
    </li>
    {% empty %}
    <li>
        <p>当前分类暂无文章发布。</p>
    </li>
    {% endfor %}
{% endarchiveList %}

This syntax is more concise and readable than usingif archives|length > 0judgments first and then loops, the code is more concise and readable.

Use a filter to provide default content or make fine judgments

exceptifAnd statementfor...emptyStructure, Anqi CMS also provides a variety of filters (filters), which can handle variable states more flexibly and provide default values.

1.defaultFilters: Set default values quickly.

When a variable does not exist or its value is considered a "falsy" value (such as an empty string,nil/false/0),defaultThe filter can immediately provide a fallback value. This is one of the most direct and commonly used methods.

{{ archive.Title|default:"无标题" }}
{{ archive.author|default:"匿名作者" }}
<img src="{{ archive.Thumb|default:"/static/images/default.jpg" }}" alt="{{ archive.Title|default:"默认图片" }}">

Ifarchive.TitleIf empty, it will display "No title"; ifarchive.ThumbIf empty, the image path will point to/static/images/default.jpg.

2.default_if_noneFilter: Precise judgmentnilValue

defaultThe filter will consider many "empty" values as defaults, but sometimes we only want to provide a default value when the variable is explicitlynila (null pointer), and distinguish between empty strings""or numbers0This can be useddefault_if_none.

{{ archive.OptionalField|default_if_none:"该字段未设置" }}

Ifarchive.OptionalFieldThe value is""(empty string) or0,default_if_noneWill not trigger the default value; only when its value isnilwill it display 'The field is not set'. This is necessary when it is necessary to strictly distinguishnilvery useful when used with null values.

3.lengthFilter: Get the length of a string or a collection.

lengthA filter can return the length of a string, array, or Map. This is useful to determine if a string isTruly emptyVery effective whether the length is 0 or whether a set contains elements.

{% if archive.Keywords|length > 0 %}
    <p>关键词:{{ archive.Keywords }}</p>
{% else %}
    <p>暂无关键词</p>
{% endif %}

This judgment is{% if archive.Keywords %}more precise because it checks the length directly rather than just judging its 'true' or 'false' nature.

By flexible applicationifStatement,for...emptyLoop structure anddefault/default_if_noneandlengthFilters, we can easily judge the existence or null status of variables in the Anqi CMS template, and display different default content as needed, thus building a more robust and user-friendly website.


Frequently Asked Questions (FAQ)

1.{% if variable %}and{{ variable|default:"默认值" }}What are the main differences in use? {% if variable %}Mainly used to control the display logic of template content, ifvariableThe value is true, then display the specific content block, otherwise displayelseblock. It does not provide a default value directly, but controls the code segment displayed when there is content or no content.{{ variable|default:"默认值" }}It focuses more on providing a default output value for the variable itself, regardless of where it is referenced, if it is empty, it will display the default value without affecting the surrounding HTML structure.

2. How do I determine if a variable isnilnot just an empty string""?Usedefault_if_noneThe filter can distinguishniland other 'falsy' values.{{ variable|default_if_none:"变量为nil" }}Only whenvariableExplicitlynilIt will show "variable is nil". Ifvariableis an empty string""or numbers0, it will output directly""or0It will not display the default value. If you need more complex logic, you can also try preprocessing at the controller level, by

Related articles

How AnQiCMS affects the display effect of the website under different template modes (adaptive, code adaptation, PC + mobile)?

When building and operating a website, we often consider how to make the website display beautifully on different devices.AnQiCMS (AnQiCMS) fully understands this point and therefore provides three flexible template modes to meet different needs: adaptive, code adaptation, and PC + mobile independent site mode.Each pattern has its unique implementation method and impact on the display effect of the website, understanding them can help us better choose the solution suitable for our project.### One, Adaptive Mode: One template, multiple screens Adaptive mode, as the name suggests

2025-11-08

How does AnQiCMS set the 'default thumbnail' to unify the display effect when images are missing?

In website content operation, images play a vital role. They can attract users' attention, enhance the visual appeal of the content, and help users quickly understand the theme of the content.However, in the process of daily content publishing, we sometimes encounter situations where some articles fail to upload exclusive thumbnails for various reasons, or the content itself does not have suitable images to extract.If the front-end page directly displays blank, broken image icons, or disordered layout, it will undoubtedly severely affect user experience and the professionalism of the website.To solve this problem, AnQiCMS

2025-11-08

How to dynamically retrieve and display the contact information of a website, such as phone number, email, and social media links?

The contact information of the website, such as phone number, email, and social media links, is an important bridge for users to connect with us.It is crucial that the accuracy and accessibility of this information is maintained in the operation of the website.AnQiCMS as an efficient content management system provides a very convenient way to manage and dynamically display this contact information, allowing us to easily maintain the consistency of website content and quickly update it when needed.This article will delve into how to set contact information in AnQiCMS, as well as how to dynamically retrieve it in templates and display it in a user-friendly manner.### One

2025-11-08

How does AnQiCMS display the table of contents or outline of the article content on the article detail page?

For articles that are rich in content and long in length, a clear table of contents or outline is like a navigation map, which can greatly enhance the reading experience of the reader.It not only helps readers quickly grasp the main points of the article, but also allows them to accurately jump to the parts of interest, thereby improving the readability and practicality of the content.In AnQiCMS, implementing the content directory display on the article detail page is not a difficult task, the built-in functions of the system provide us with a simple and efficient solution.### AnQiCMS How to understand the article structure? AnQiCMS

2025-11-08

How to concatenate an array into a string with a specified delimiter for display in AnQiCMS?

AnQiCMS flexibly handles data in templates, which is the key to enhancing the website display effect for content operators.Among them, concatenating the array into a string with a specified separator is a common need to improve the readability and aesthetics of the content.Benefiting from the powerful and flexible template engine of AnQiCMS, especially its built-in rich filter functions, we can easily achieve this goal.

2025-11-08

How to split a string into an array with a specified delimiter and iterate through it in AnQiCMS?

In website operation, we often encounter the need to store some seemingly simple, but actually containing multiple pieces of information data in an article, a product description, or some custom field.For example, multiple tags of a blog, multiple features list of a product, or some dynamic display related words.These data are usually connected into a long string with a specific delimiter (such as a comma, semicolon, or pipe).

2025-11-08

How to display the current year or a custom time format in AnQiCMS templates?

In website operation, the accuracy and display of time information has a significant impact on user experience and content professionalism.Whether it is the copyright year in the footer or the publishing or updating time of the article content, a clear and consistent date format can enhance the overall perception of the website.AnQiCMS provides very flexible and powerful features in templates to meet these time display requirements.### Show the current year: Use the `{% now %}` tag to quickly display Many website footers display the current year as part of the copyright statement, for example “© 2023

2025-11-08

How to ensure that the custom system parameters set in the AnQiCMS backend can be correctly displayed in the frontend template?

The flexible application of custom system parameters in Anqi CMS is the key to improving website maintainability and operational efficiency.Many times, we may need some information that is not covered by the default system fields, such as specific external links, additional corporate honor information, or exclusive copywriting for a specific event.AnQi CMS provides a convenient way to add these custom parameters and ensures they are presented accurately in the front-end template.### One, understand the setting location of custom system parameters Firstly, we need to clarify the setting entry of custom system parameters in the Anqi CMS background

2025-11-08