When building website templates, we often encounter situations where a variable may be empty in the template due to data not being entered, optional fields being left blank, or specific business logic.If these empty variables are not processed, the website front-end page may appear blank areas, display unfriendly placeholders, or even cause layout disorder, thereby affecting the user experience and the professionalism of the website.
Luckily, AnQiCMS provides two elegant and practical methods to help us set a default friendly display value for possibly empty variables in the template, ensuring the integrity and aesthetics of the website content.
1. UsedefaultFilter: The preferred option for simplicity and efficiency
When you want to directly display a preset text or image path when the variable is empty,defaultThe filter is the most direct and simplest choice. It can detect if a variable is empty (includingnilis an empty string orfalsesuch 'falsy' values), and if it is empty, it will output the default value you specified.
For example, if the "Contact Phone" field is not filled in on your website, the front-end may display a blank space. ThroughdefaultFilter, we can handle it like this:
Assuming you have passed.{% contact cellphone with name="Cellphone" %}Gained the contact information and assigned tocellphoneVariable.
<span>联系电话:{{ cellphone|default:"暂无联系电话" }}</span>
IfcellphoneA variable has a value (for example, “13888888888”), and the page will display “Contact phone: 13888888888”. IfcellphoneThe variable is empty, the page will display
For example, documents usually have thumbnails, but if some documents do not upload thumbnails, we do not want the page to show an icon indicating missing images. We can set a default image path:
<img src="{{ archiveThumb|default:"/public/static/images/default-thumb.png" }}" alt="文档缩略图"/>
HerearchiveThumbVariables may come from{% archiveDetail archiveThumb with name="Thumb" %}IfarchiveThumbIf valid, use it; otherwise, it will loaddefault-thumb.pngThis default image.
AnQiCMS also providesdefault_if_noneFilter. It isdefaultSimilar, but only for values ofnilThe condition takes effect, but will not handle empty strings orfalse. In most cases where a friendly default value is needed,defaultthe filter is sufficient to meet the needs.
2. CombinedifLabel for conditional judgment: An advanced customized solution
In some cases, simply replacing a default text is not enough, you may need to render a completely different HTML structure or perform more complex logic based on whether a variable exists. At this point,ifthe tag comes into play.
ifThe tag allows you to execute a code block when a variable exists (non-empty), or to execute another code block when the variable does not exist, or to perform no operation.
For example, a category page may have a Banner image, but not all categories do. If a Banner image exists, we want to display one<img>Label, if not exists, then display a piece of introduction text or a default background color block.
First, get the variable of the category Banner image:
{% categoryDetail categoryBanner with name="Logo" %}
Then, use it in the templateifLabel for judgment:
{% if categoryBanner %}
<div class="category-banner">
<img src="{{ categoryBanner }}" alt="分类Banner"/>
</div>
{% else %}
<div class="category-info">
<h3>欢迎来到 {{ categoryTitle }} 页面</h3>
<p>这里是分类的简介内容...</p>
</div>
{% endif %}
In this way, you can design different display forms for the 'existence' and 'non-existence' of variables according to the actual situation, making the page more dynamic and user-friendly.
3. Advanced Application: Handling Content with HTML
When the default value you set or the variable itself may contain HTML code, in order to ensure that these HTML codes are correctly parsed by the browser and not displayed as plain text, you need to use|safeFilter. AnQiCMS template engine, for safety reasons, defaults to escaping all output content to prevent cross-site scripting (XSS) attacks.|safeThe filter explicitly tells the template engine that you are sure this content is safe and does not need to be escaped.
For example, the copyright information at the bottom of a website may include©etc. HTML entities or<p>Label. If the copyright content may be empty, and you want to provide a default value containing HTML tags:
{% system siteCopyright with name="SiteCopyright" %}
<div class="footer-copyright">
{{ siteCopyright|default:"© AnQiCMS 版权所有. 保留所有权利."|safe }}
</div>
Here, |safeEnsured©It can be correctly parsed as a copyright symbol, rather than being output as is. Similarly, ifsiteCopyrightthe variable itself contains<a>links or other HTML structures,|safeare also indispensable.
By flexible applicationdefaultFilters andifTags, combined with|safeThe filter processes HTML content, you can easily handle empty variables in the AnQiCMS template, thus building a stronger, better user experience website.
Frequently Asked Questions (FAQ)
Q1:defaultanddefault_if_noneWhat are the differences between filters?
A1:defaultThe filter is applied when the variable isnilan empty string""and a boolean valuefalseor numbers0or any 'falsy' value. While thedefault_if_nonefilter is more strict, it will only be applied when the variable's value isnil(which means that the default value is applied when undefined or NULL in the database) and will not process empty strings orfalseother false values. In most cases, usedefaultThe filter will be more universal and convenient.
Q2: Why do I sometimes need to add after the default value?|safe?
A2: AnQiCMS template engine, for website security, defaults to escaping all output variable content, converting<to<,>to>To prevent malicious script injection (XSS attacks). If the default value or variable you set itself contains legitimate HTML code (such as<p>这是一个段落</p>),and hope that these HTML codes can be parsed and displayed by the browser, rather than as plain text.|safeThe filter tells the template engine that this content is safe and does not need to be escaped.
Q3: Can I set a default value for a variable of list or array type? For example, when an image list is empty, can I display a default image?
A3: Yes.defaultThe filter applies to lists or arrays as well. If a list or array variable is empty (i.e., has a length of 0),defaultThe filter will directly output the default value you have set for it. However, it is important to note that if you still want the default value to be a list or array structure, you may need to combineifLabel judgment, or set the default value to an array string containing the default elements and cooperate|listFilter processing. But for the scenario of displaying a single default image, use it directly{{ item.Images|first|default:"/public/static/images/placeholder.png" }}orif item.ImagesLogic handling is more common in it.