As an experienced website operations expert, I know that handling empty variables is the key to ensuring the quality of website content and user experience when building and maintaining website templates.In AnQiCMS (AnQiCMS) such a flexible and efficient content management system, the flexible use of template variables is its strength, but at the same time, how to elegantly set reliable default values for possible empty variables to avoid ugly blank spaces on the page or functional exceptions is an art worth in-depth exploration.
Today, we will share some practical and efficient strategies on how to set reliable default values for empty variables in Anqi CMS templates.
Why does an empty variable become a problem?
During the operation of the website, uncertainty in content is the norm.For example, an article may not have an image, a product description may be temporarily missing, or a custom field may not be applicable to certain content types.When these variables corresponding to the template are empty, if the template is not handled properly, the front-end page will directly display a blank space, or output some unfriendly placeholders, which not only ruins the overall aesthetics of the website, reduces the user experience, but may also affect the SEO performance, because search engines also prefer complete and structured pages.Therefore, setting a default value for variables that may be empty is an important guarantee for improving the robustness and user satisfaction of the website.
AnQiCMS uses a syntax similar to the Django template engine, where variable output is done using double curly braces{{变量}}Logic control uses single curly braces and percent signs.{% 标签 %}This syntax provides powerful flexibility and offers us various clever methods for handling empty variables.
Method one: utilizedefaultanddefault_if_noneFilter, the simplest default value setting
In the AnQiCMS template,defaultanddefault_if_noneIt is the most direct and concise way to handle empty variables. They are all used as filters (filters) to provide alternative content for variables easily.
1.defaultFilter
defaultThe filter applies to variables asnilThe situation of 'false values' such as empty strings, empty lists, or empty dictionaries. It is the most commonly used default value setting method, which can cover the vast majority of empty value scenarios.
- How to use:
{{ 变量 | default:"你的默认值" }} - Example:Assuming we have a variable for the article title
archive.Titleand a variable for the article descriptionarchive.Description.
<h1>{{ archive.Title | default:"暂无标题" }}</h1>
<p>{{ archive.Description | default:"该文章暂无简介,敬请期待。" }}</p>
<img src="{{ archive.Logo | default:"/static/images/default_logo.png" }}" alt="{{ archive.Title | default:"默认图片" }}">
In this example, ifarchive.Titleis empty, the page will display "No title available"; ifarchive.DescriptionIf empty, it will display 'This article has no introduction, please wait.';“Ifarchive.LogoIf empty, it will use a preset default image path.
2.default_if_noneFilter
default_if_noneThe filter is more accurate, it only matches if the variable isnilAn empty pointer is effective onlynilfor handling null values. This is useful in situationsnilwhere it is necessary to distinguish
- How to use:
{{ 变量 | default_if_none:"你的默认值" }} - Example:consider a situation where it may be
nilUser object of theuser.RealName.
<p>用户姓名:{{ user.RealName | default_if_none:"匿名用户" }}</p>
Ifuser.RealNameIsnilit will display "Anonymous User"; but ifuser.RealNameIs an empty string"",default_if_noneit will not trigger, the page will display an empty string. If you want to handle an empty string, you still need to usedefaultfilter.
Method two: cleverly useif/elseLogic judgment label, implementing more complex default logic
When the setting of the default value requires more complex logical judgment, or the default value itself needs to be dynamically generated according to other conditions, AnQiCMS is powerfulif/elseLogical judgment labels come into play. They provide a finer level of control.
- How to use:
{% if 变量 %} {{ 变量 }} {% else %} 你的默认值 {% endif %} - Example:Assuming we want to automatically extract the first image as the default image if there is an image in the content when there is no thumbnail in the article; otherwise, a generic placeholder will be displayed.
{% if archive.Thumb %}
<img src="{{ archive.Thumb }}" alt="{{ archive.Title | default:"文章标题" }}">
{% elif archive.ContentImages %} {# 假设存在一个字段 archive.ContentImages 存储内容中的所有图片 #}
<img src="{{ archive.ContentImages | first }}" alt="{{ archive.Title | default:"文章标题" }}">
{% else %}
<img src="/static/images/no_image.png" alt="暂无图片">
{% endif %}
This method may be slightly longer than the filter, but its advantage lies in its ability to handle multi-level judgment logic, and even call other tags or perform more complex calculations inelsea block.
Method three: cooperatesetorwithLabel preset variables, improve template maintainability
In some cases, a possibly empty variable may be referenced multiple times in a template, and each reference needs to apply the same default value logic. At this point, we can usesetorwithLabel the processed variable (including default values) and assign it to a new variable, then refer to this new variable multiple times. This can effectively avoid code repetition and improve the maintainability of the template.
setTags:Define a variable within the current scope.withTags:Define a variable within a block scope, usually used to pass variables toinclude.Example:Assume
archive.SeoTitleMay be empty, we want to set a default value, and this value will be used in<head>and<h1>tags. It will be used in all tags.
{# 使用 set 标签预设变量 #}
{% set pageTitle = archive.SeoTitle | default:archive.Title | default:"网站通用标题" %}
<head>
<title>{{ pageTitle }}</title>
<meta name="description" content="{{ archive.Description | default:"网站通用描述" }}">
</head>
<body>
<h1>{{ pageTitle }}</h1>
{# 页面其他地方也直接使用 pageTitle #}
</body>
Here, we usesettags at one time forpageTitledetermined the final display value. Ifarchive.SeoTitleIf it is not empty, use it; otherwise, try using itarchive.Title; ifarchive.TitleIf it is also empty, use the "General Title of the Website". This way, it only needs to be referenced in the templatepageTitleIt is clear and avoids repetition.
Combine content model to set backend default values (auxiliary strategy)
In addition to setting default values at the template level, we can also directly set default values for custom fields in AnQiCMS's content model (configured through "Content Management" -> "Content Model").This is an auxiliary strategy to solve the 'null value' problem at the data source level.
In the settings of custom fields,