During the development of website templates, it is common to encounter situations where variable values may be empty. If not handled properly, the front-end page may display unattractive blank areas or some default placeholders (such asnilornullThis undoubtedly affects user experience and the professionalism of the website.AnQiCMS (AnQiCMS) provides a powerful and flexible template engine that can help us elegantly determine whether a variable is empty and set an appropriate default display value for them.
Understanding AnQiCMS templates in English
In AnQiCMS templates, a variable is considered 'empty' under the following circumstances:
nilValues:When a variable is not assigned or its value is anil.- An empty string:For
"". - The number zero:
0. - Boolean value
false:Although it is technically not 'empty', it is considered false in conditional judgments. - Empty array, slice, or map:When a variable is a collection type but does not contain any elements.
Understanding these 'empty' states is crucial for correctly performing conditional judgments and setting default values.
Use{% if %}tags for conditional judgments
The most direct method to handle an empty variable is to use the AnQiCMS template engine provided{% if %}The condition judgment tag. This tag allows you to display different content based on whether the variable exists or has a valid value.
When you use{% if 变量名 %}such a form, the template engine will automatically detect whether the variable is the 'empty' state mentioned earlier. If it is, the conditional judgment result is false (false), otherwise it is true (true).
For example, you may want to display a thumbnail of the article on a detailed article page. If the article does not have a thumbnail, a default placeholder image will be displayed:
{% if archive.Thumb %}
<img src="{{ archive.Thumb }}" alt="{{ archive.Title }}" class="article-thumbnail">
{% else %}
<img src="/static/images/default_thumbnail.png" alt="默认图片" class="article-thumbnail">
{% endif %}
In the above example,archive.ThumbIs the thumbnail address of the document.archive.ThumbExists and is not an empty string, the actual thumbnail will be displayed; otherwise,/static/images/default_thumbnail.pngThis default image will be displayed.
Similarly, if the document description informationarchive.Descriptionmay be empty, you can handle it like this:
{% if archive.Description %}
<p class="article-description">{{ archive.Description }}</p>
{% else %}
<p class="article-description">暂无简介。</p>
{% endif %}
This method is clear and straightforward, suitable for scenarios where different structures or long texts need to be displayed based on whether a variable is empty.
Set default display value: Use a filter
Except{% if %}标签外,AnQiCMS 模板引擎还提供了功能强大的过滤器(filters),它们可以更简洁地处理变量为空并设置默认显示值的问题。特别是defaultanddefault_if_noneThese filters can directly judge and provide alternative values when variables are output.
1.defaultFilter
defaultFilters will be triggered when variables are evaluated as "empty" (includingnilAn empty string"", or a number0, boolean valuefalseWhen the value is empty or an empty collection), replace it with the default value you specified. This is the most commonly used method for setting default values, as it covers most "no content" cases.
The usage is as follows:
{{ 变量名|default:"默认显示内容" }}
For example,archive.TitleMay be empty, you can ensure it always has a friendly display like this:
<h1>{{ archive.Title|default:"无标题文章" }}</h1>
For the number of views of the articlearchive.Viewsif its value is0you might want to display it as '0 times read' instead of blank:
<span>{{ archive.Views|default:0 }}次阅读</span>
Even the thumbnail examples above can bedefaultFilter simplification:
<img src="{{ archive.Thumb|default:"/static/images/default_thumbnail.png" }}" alt="{{ archive.Title|default:"无标题" }}" class="article-thumbnail">
This one line of code can accomplish what{% if %}was previously only possible with multi-line tags, making the template code more compact and readable.
2.default_if_noneFilter
default_if_noneFilter is related todefaultsimilar, but it has a key difference: itonly when the value of the variable isnil(null pointer)the default value is applied. If the variable is an empty string""or a number0,default_if_noneWill not interfere, but directly output these "non"nilvalues that are empty."
This is very useful in certain specific scenarios, for example, when you want to distinguish a value that is "unset".nil)and a "clearly set to blank" value"").
The usage is as follows:
{{ 变量名|default_if_none:"默认显示内容" }}
Assuming you have a user-defined fielduser.Signatureif the user has not set a signature, it may benil。If the user has set it, they have just set an empty string, and you want to retain the display of this empty string (perhaps for stylistic considerations), in which case you can usedefault_if_none:
<p>个性签名:{{ user.Signature|default_if_none:"该用户很神秘,没有留下签名。" }}</p>
Ifuser.SignatureYesnil,将显示“The user is mysterious, no signature left.”;但如果user.SignatureYes"",则会显示空行,这与defaultfilterer (it will replace"")的行为有所不同。
practical application
In actual projects, you can flexibly choose according to specific requirements{% if %}tags,defaultFilter ordefault_if_noneFilter.
- Prefer to use filters:For simple variable output with a single default value,
defaultordefault_if_noneThe filter is usually a more concise and efficient choice. - Complex condition logic:When you need to render a completely different HTML structure based on whether a variable is empty, or when multiple branching logic is involved,
{% if %}Tags and their{% elif %}and{% else %}the structure will provide better readability and control. - Custom field default value:For custom fields (such as
archive.Author), if the value may be empty, use{{ archive.Author|default:"佚名" }}the filter to easily set a default value.
Master these skills, and you will be able to build robust, beautiful, and user-friendly AnQiCMS website templates with greater ease.
Common Questions (FAQ)
When should it be used
defaultFilter, when to usedefault_if_noneFilter?defaultApplicable to most cases. As long as the variable isnilAn empty string"", or a number0, boolean valuefalseor an empty set, it will be replaced by the default value. If you only care about whether the variable has valid content to display,defaultit is your best choice.default_if_noneonly when the value of the variable isnilOnly takes effect when specified. If you need to clearly distinguish between 'a variable has never been assigned'nil) and 'a variable is explicitly assigned to blank or zero'""or0),and there are different handling logic for these two cases.default_if_nonewill be more useful.
Can these methods of determining whether variables are empty be used for custom fields in the AnQiCMS content model?
- Yes, it is absolutely. The way AnQiCMS template engine handles core fields and custom fields is consistent. Whether it is for the document's
archive.Titleor the ones you add to the content modelarchive.CustomField,You can use it{% if archive.CustomField %}to make a judgment, or use{{ archive.CustomField|default:"自定义字段默认值" }}to set the default display value.
- Yes, it is absolutely. The way AnQiCMS template engine handles core fields and custom fields is consistent. Whether it is for the document's
How to judge whether a list or array is empty and display the corresponding message?
- When you use
{% if 列表变量 %}When, the template engine will automatically determine whether the list variable contains any elements. If the list is empty (i.e., no elements), the condition judgment result is false. You can combine{% else %}Display prompts such as 'No data available'. For example:{% if archives %} {% for item in archives %} <!-- 显示文章列表内容 --> {% endfor %} {% else %} <p>很抱歉,当前没有找到相关文章。</p> {% endif %} - In addition,
{% for %}Loop labels are also provided.{% empty %}clauses can be executed when the collection in the loop is empty, which is a more concise way: “`twig {% for item in archives %}
- When you use