How to set default display values for possibly null variables, strings, or objects?

In website content management, data integrity and consistency are crucial.However, in actual operation, we often encounter situations where certain variables, strings, or objects may be empty.If the template does not handle these null values properly, the front-end page may appear blank, disordered, or even report errors, seriously affecting user experience.AnQiCMS (AnQiCMS) provides a variety of flexible and powerful template tags and filters, helping us elegantly handle these potential null values, ensuring the stability and beauty of the website content.

The template system of Anqi CMS has borrowed the syntax of Django, it provides a series of intuitive tools to set default display values, allowing even areas without content to be displayed properly, thereby enhancing the professionalism and user satisfaction of the website.

核心策略一:英语翻译为English:Use default value filters wisely

In the templates of AnQi CMS,default过滤器是一个非常实用的工具,它允许我们为可能为空或未定义的变量设置一个备用值。当变量的值是英语翻译为English:The filter is a very practical tool that allows us to set a default value for variables that may be empty or undefined. When the value of the variable isfalse/0An empty string""If empty or a list is empty,defaultthe filter comes into play.

For example, if your article title variable,item.Titleit may be empty. You don't want to have a blank space on the page, but instead display a default prompt, you can use it like this:{{ item.Title|default:"无标题内容" }}In this way, even though item.TitleEmpty, the page will also display "No title content".

Another closely related filter isdefault_if_none. It complementsdefaultSimilar, but more focused on handlingnil(i.e., in Go language)null) value. In some cases, the variable may be explicitly set tonilIt is not an empty string or zero. At this point,default_if_noneyou can ensure that you set a fallback value.{{ someVariable|default_if_none:"N/A" }}This filter is particularly effective when dealing with fields that may be empty from database queries, as it helps ensure that the page displays friendly and complete information.

核心策略二:利用条件判断实现灵活控制

当您需要根据变量是否存在或是否为空来决定显示不同的内容结构时,ifThe logical judgment tag becomes your helpful assistant. It allows you to write more complex conditional logic to meet diverse display needs.

For example, when displaying a thumbnail of an article or category, you may want to show it only if the image actually exists<img>Tag, otherwise do not display, or display a placeholder image:

{% if item.Thumb %}
  <a href="{{ item.Link }}">
    <img src="{{ item.Thumb }}" alt="{{ item.Title|default:'图片' }}">
  </a>
{% else %}
  {# 如果没有缩略图,可以显示一张默认的占位图 #}
  <a href="{{ item.Link }}">
    <img src="/static/images/default-thumb.png" alt="{{ item.Title|default:'默认图片' }}">
  </a>
{% endif %}

Pass{% if ... %}and{% else %}Structure, you can provide multiple safeguards for content to ensure that the page presents itself gracefully regardless of the data status.

Core Strategy Three: An elegant way to handle empty lists

When displaying content such as article lists, comment lists, or friend links, data is usually provided in the form of arrays or slices.If this list is exactly empty, direct traversal may cause the page to be blank.forLoop tags provide a{% empty %}Branch used specifically to handle the case where the list is empty.

For example, when displaying a list of articles:

{% archiveList archives with type="page" limit="10" %}
    {% for item in archives %}
    <li>
        <a href="{{ item.Link }}">
            <h5>{{ item.Title|default:'暂无标题' }}</h5>
            <div>{{ item.Description|default:'暂无简介' }}</div>
        </a>
    </li>
    {% empty %}
    <li>
        <p>当前分类下暂无文章,敬请期待!</p>
    </li>
    {% endfor %}
{% endarchiveList %}

This method is better than adding outside offora loop an extra timeifThe judgment is more concise and readable, combining the logic of 'iteration' and 'empty state handling' tightly.

Practical application scenarios

Apply these strategies to the daily display of website content, which can greatly enhance the robustness of the template and the user experience:

  1. Website title, keywords, and description (TDK):UsetdkLabeling the page TDK information can be combined withdefaultFilter to ensure that even if the backend is not filled in, the front-end has a reasonable default value display.<title>{% tdk with name="Title" siteName=true %}|{% system with name="SiteName"|default:"我的网站" %}</title> <meta name="description" content="{% tdk with name="Description" %}|{% system with name="SiteName"|default:"这是一个提供优质内容的网站" %}">

  2. Images and links in the content details:In the article or product detail page, if the Logo or specific image field may be empty, you can use conditional judgment to display the default image or hide the image placeholder.{% archiveDetail logo with name="Logo" %} {% if logo %}<img src="{{ logo }}" alt="{% archiveDetail with name='Title' %}" />{% else %}<img src="/static/images/default-product.jpg" alt="默认产品图片" />{% endif %}

  3. Custom field display:When custom fields are defined in the content model but not all content may be filled in,defaultthe filter can avoid blank output.{% archiveParams params with sorted=false %} {% if params.author %}<p>作者: {{ params.author.Value|default:"匿名作者" }}</p>{% endif %}or directly in the loop:<span>{{ item.Name }}:{{ item.Value|default:"未填写" }}</span>

  4. Contact information or friendship link:Even if contact information or friendship link is not set, you can stillifControl the display of the entire block with judgment to avoid unnecessary empty areas.{% contact cellphone with name="Cellphone" %} {% if cellphone %}<div>联系电话:{{ cellphone }}</div>{% endif %}

By proficiently using these template techniques, you will be able to build more stable, professional, and user-friendly security CMS websites.


Common Questions (FAQ)

Q1:defaultanddefault_if_noneFilter what are the main differences in the Anqi CMS template?A1: The main difference lies in their definition of 'empty'.defaultFilters handle various 'empty' values, including empty strings"", or a number0, boolean valuefalseand empty lists, etc.default_if_nonethe filter is more strict, it only takes effect when the variable's value isnil(i.e., in Go language),null). This means that if you want to set a default value for a variable that indeed has no value,default_if_noneMore precise; if a variable may appear to be empty for various reasons (such as an empty string or zero),defaultit is more general.

Q2: How do I set a default placeholder image for images that may not exist in the template?A2: You can useifSentence combinationdefaultOr directly specify the default image path. For example, for article thumbnailsitem.Thumb:

{% if item.Thumb %}
  <img src="{{ item.Thumb }}" alt="{{ item.Title|default:'文章图片' }}">
{% else %}
  <img src="/static/images/placeholder.jpg" alt="默认占位图">
{% endif %}

to/static/images/placeholder.jpgReplace it with the actual default image path.

Q3: When myarchiveListorcategoryListThe tag query result is empty, how can you prompt the user 'No content' in a friendly manner?A3: You canforLooping label inside usage{% empty %}tags to handle this situation. Whenforthe list being traversed is empty,{% empty %}The content inside the block will be rendered.

{% archiveList archives with type="list" categoryId="1" limit="10" %}
    {% for item in archives %}
        {# 正常显示文章内容的 HTML 代码 #}
        <p>{{ item.Title }}</p>
    {% empty %}
        {# 列表为空时显示的内容 #}
        <p>抱歉,此分类下暂无文章发布。</p>
    {% endfor %}
{% endarchiveList %}

This method provides a concise, efficient, and easy-to-maintain solution for handling empty content.