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