How to judge whether a variable is empty in AnQiCMS template and set a default display value?

During the development of website templates, it is often encountered that variable values may be empty. If not handled properly, the front-end page may appear with unattractive blank areas, or even display 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.

Understand the 'empty' in AnQiCMS templates

In AnQiCMS templates, a variable is considered 'empty' usually in the following cases:

  • nilValue:When a variable has not been assigned a value or its value is in Go languagenil.
  • Empty string:As"".
  • The number zero: 0.
  • Booleanfalse:Although technically not 'empty', it is considered false in conditional judgments.
  • An empty array, slice, or map:When the variable is a collection type but does not contain any elements.

Understanding the state of 'empty' is crucial for performing conditional judgments and setting default values correctly.

Use{% if %}tag for conditional judgment

The most direct method to handle an empty variable is to use the template engine provided by AnQiCMS{% if %}Conditional tag. This tag allows you to display different content based on whether the variable exists or has a valid value.

When you use{% if 变量名 %}When this form is, 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 is 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. Ifarchive.ThumbIf the string exists and is not empty, the actual thumbnail will be displayed; otherwise, it will display/static/images/default_thumbnail.pngthis default image.

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 large blocks of text need to be displayed based on whether a variable is empty.

Set default display value: using filters

except{% if %}Outside the tag, AnQiCMS template engine also provides powerful filters (filters) that can handle empty variables and set default display values more simply. In particular,defaultanddefault_if_noneThese filters can directly judge and provide alternative values when variables are output.

1.defaultFilter

defaultFilters will be evaluated as "empty" (includingnilan empty string""numbers0and a boolean valuefalseWhen the content is empty or a null set, replace it with the specified default value. This is the most common way to set a default value, as it covers most cases of 'no content'.

How to use:

{{ 变量名|default:"默认显示内容" }}

For example, ifarchive.TitleMay be empty, you can ensure it always has a friendly display:

<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 mentioned above can be useddefaultFilter simplification:

<img src="{{ archive.Thumb|default:"/static/images/default_thumbnail.png" }}" alt="{{ archive.Title|default:"无标题" }}" class="article-thumbnail">

This line of code can complete what was previously{% if %}Functionality that required multiple lines of tags, making the template code more compact and readable.

2.default_if_noneFilter

default_if_nonethe filter meetsdefaultIt is similar, but it has a key difference: itonly when the value of the variable isnil(null pointer) appliesthe default value. If the variable is an empty string""or a number0,default_if_noneThese 'non'-intervening values will be output directly.nilThese values are empty.

This is very useful in certain scenarios, for example, when you want to distinguish a 'not set' value (nil)and a "clearly set to blank" value("")

How to use:

{{ 变量名|default_if_none:"默认显示内容" }}

Assuming you have a custom user fielduser.Signature,if the user has not set a signature, it may benil. But if the user has set it, and just set an empty string, you want to retain the display of this empty string (perhaps for styling considerations), then you can usedefault_if_none:

<p>个性签名:{{ user.Signature|default_if_none:"该用户很神秘,没有留下签名。" }}</p>

Ifuser.SignatureIsnilIt will display “This user is very mysterious, no signature left.”; but ifuser.SignatureIs""it will display a blank line, which is different fromdefaultthe filter (which will replace""‘s behavior is different."),

combined application in practice

In a real project, you can flexibly choose according to specific needs{% if %}tags,defaultOr filter.default_if_nonefilter.

  • Prioritize using the filter:In the case of simple variable output with a single default value,defaultordefault_if_noneFilters are usually a more concise and efficient choice.
  • Complex conditional logic:When you need to render completely different HTML structures based on whether a variable is empty, or contain multiple branch logic,{% if %}tags and their{% elif %}and{% else %}the structure will provide better readability and control.
  • Custom field default value:For custom fields in the backend content model (such asarchive.Author), if the value may be empty, use{{ archive.Author|default:"佚名" }}the filter to easily set the default value.

Master these skills and you will be able to build strong, beautiful, and user-friendly AnQiCMS website templates more skillfully.


Frequently Asked Questions (FAQ)

  1. When should it be useddefaultFilter, when to usedefault_if_noneFilter?

    • defaultSuitable for most cases. As long as the variable isnilan empty string""numbers0and a 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, thendefaultis your first choice.
    • default_if_noneonly when the variable's value isnilOnly when activated. If you need to clearly distinguish between a variable that has never been assigned a value (nil) and a variable that has been explicitly assigned as blank or zero (""or0),and then it will handle these two cases differentlydefault_if_noneWill be more useful.
  2. Can these methods to judge whether variables are empty be used for the custom fields in the AnQiCMS content model?

    • Certainly, it can be done. The AnQiCMS template engine handles core fields and custom fields in the same way. Whether it is thearchive.Titleor the fields you add to the content model.archive.CustomFieldYou can all use{% if archive.CustomField %}to judge, or use{{ archive.CustomField|default:"自定义字段默认值" }}to set the default display value.
  3. 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., there are no elements), the condition evaluation result is false. You can combine{% else %}Display "No data" prompts, for example:
      
      {% if archives %}
        {% for item in archives %}
          <!-- 显示文章列表内容 -->
        {% endfor %}
      {% else %}
        <p>很抱歉,当前没有找到相关文章。</p>
      {% endif %}
      
    • Furthermore,{% for %}Loop tags are also provided.{% empty %}A clause that can execute its content when the loop collection is empty, which is a more concise way: “`twig {% for item in archives %}