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

Calendar 👁️ 65

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 %}

Related articles

How to dynamically display the Title, Keywords, and Description information of the website homepage in AnQiCMS template?

In website operation, the Title (title), Keywords (keywords), and Description (description) of the homepage are the first impression given to users on the search engine results page (SERP) and are also the key for search engines to understand the core content of the website.They not only affect the website's search engine optimization (SEO) effect, but also directly relate to whether users will click to enter your website.AnQiCMS as a feature-rich enterprise-level content management system provides a straightforward and powerful way to manage these important SEO elements. Next

2025-11-07

How to display all the Tag tags belonging to the current article in AnQiCMS template?

Flexible display of article tags in AnQiCMS templates Tags are a highly effective content organization method in website content operation.They can not only help users find relevant content faster, enhance the browsing experience of the website, but also have an indispensable positive effect on search engine optimization (SEO).AnQiCMS as a feature-rich enterprise-level content management system naturally also provides powerful tag management and call functions, allowing us to easily display all tags associated with the current article on the article detail page.

2025-11-07

How to get and display related article lists according to Tag ID in AnQiCMS template?

In a content management system, Tag (tag) plays an important role.They can not only help us flexibly organize content, but also associate articles with similar themes across different categories, and can effectively improve the website's internal link structure and user experience.When a user is interested in a specific topic, by clicking on a Tag, they can easily view all related articles.AnQiCMS provides a set of intuitive and powerful template tags that allow you to easily retrieve and display these related article lists based on Tag ID.

2025-11-07

How to automatically generate and display the content directory (ContentTitles) on the article detail page of AnQiCMS?

## How to automatically generate and display the content directory (ContentTitles) on the AnQiCMS article detail page??For long content, a clear table of contents (also known as "article outline" or "chapter navigation") can greatly enhance the reading experience of users.It not only helps readers quickly understand the structure of the article, but also allows them to directly jump to the chapters of interest, thereby improving the readability and user satisfaction of the content.

2025-11-07

How to truncate a long string (such as an article summary) to a specified length and display an ellipsis in the AnQiCMS template?

In website content operation, the display length of article abstracts or introductions often needs careful control.Long content can affect the layout and user experience of a page, while a concise summary with an ellipsis can effectively guide users to click and read more details.AnQiCMS provides flexible template tags and filters, allowing us to easily implement this feature.

2025-11-07

How to remove specific HTML tags from an HTML string in the AnQiCMS template (such as `<i>`, `<span>`)?

In AnQiCMS template development, we often encounter content coming from rich text editors, or imported from external sources, which may contain some HTML tags that we do not want to display at specific locations.For example, in the summary section of the article list, we may only want to display plain text, or we may need to remove specific tags such as `<i>`, `<span>`, etc. to maintain the consistency of the page style.

2025-11-07

How to convert newline characters in multi-line text to the HTML `<br>` tag for display in AnQiCMS templates?

In AnQiCMS content management, we often enter multi-line text with line breaks, such as article content, product descriptions, or contact addresses.However, when this content is displayed on the website front-end, we may find that the original clear line breaks are missing, and all the text is squeezed into a single line.This not only affects the reading experience of the content, but may also be inconsistent with our original design intention.Why is this happening?

2025-11-07

How to calculate the number of elements in a string (such as an article title) or an array (such as a tag list) in AnQiCMS templates?

In AnQi CMS template design, we often need to make accurate statistics of the content on the page, whether it is to dynamically display the number of data or to make conditional judgments based on the number, mastering how to calculate the number of elements in a string or array is particularly important.AnQiCMS's powerful template engine provides a concise and efficient method to handle these requirements.

2025-11-07