How can you determine if a variable (such as the article title) exists or is empty in a template and display a custom default value?

It is crucial to ensure the completeness of content and the user experience in website content management.Sometimes, due to missing content or unassigned variables, blank areas or error messages may appear on web pages, which undoubtedly affects the professionalism of the website.The template engine of AnQiCMS provides a flexible and powerful mechanism to help users elegantly handle these situations, even if the variables do not exist or are empty, ensuring the robust presentation of page content.

In AnQiCMS template design, we often encounter situations where we need to display a variable (such as article title, description, image URL, etc.).However, in actual operation, these variables may be missing for various reasons.This is when we need a method to determine their existence, and provide a custom default value if necessary, to avoid the page looking empty or displaying errors.

The basic idea of variable existence and null value judgment

The AnQiCMS template engine uses syntax similar to Django, which means we can take advantage ofifLabel conditional judgment. This is the most direct method to handle the existence or null value of a variable.

When we want to judge whether a variable (such as)archive.Title, that is, the article title) has a value, we can use it directly.{% if 变量名 %}Such a structure. This judgment method checks if the variable is a non-empty string, non-zero number, ornilAn object or a non-empty collection. If the variable has actual content, the condition is true; otherwise, it is false.

For example, if you want to display a default prompt when the article title is empty:

{% if archive.Title %}
    <h1>{{ archive.Title }}</h1>
{% else %}
    <h1>暂无文章标题</h1>
{% endif %}

If you need to precisely determine whether a variable is an empty string rather than simply 'no value', you can explicitly compare it with an empty string:

{% if archive.Title == "" %}
    <h1>内容正在编辑中...</h1>
{% else %}
    <h1>{{ archive.Title }}</h1>
{% endif %}

Gracefully set default values using a filter

AlthoughifJudging can solve the problem, but in some scenarios, the CMS provides a more concise and elegant way to handle the default values of variables - that is, using filters. In which,defaultanddefault_if_noneThese two filters are the tools to meet this requirement.

defaultFilters are very practical. When a variable isnil(null pointer), empty string or some type of zero value (such as the number 0) when it will output the default value you provide. This means you do not need to explicitly writeif-elseStructure, that is, to set a fallback content for possibly empty variables.

For example, set a default value for the article title:

<h1>{{ archive.Title|default:"未命名文章" }}</h1>

The meaning of this code is: ifarchive.TitleIf there is a value, display it; if not, display 'Unnamed Article'.

Another isdefault_if_noneFilter. If you only need to setnildefault values for the situation of (null pointer), but want to display empty strings or zero values normally, thendefault_if_noneWould be a more precise choice. In practical applications, since most content variables in the database are stored as empty strings if there is no value,defaultfilters are usually more general and commonly used.

For example, if you only want to displayarchive.Titleresponse fornildefault value when it is time, but an empty string itself is also valid content:

<h1>{{ archive.Title|default_if_none:"标题信息缺失" }}</h1>

However, in the regular use of AnQi CMS, variables usually either have an explicit value or are empty strings,nilare relatively rare, sodefaultThe filter is sufficient to handle the vast majority of scenarios.

Combined with specific scenarios: taking the article title as an example

Let us take a common article detail page as an example, and see how to apply these techniques in actual templates.假设我们正在设计一个文章详情模板,需要显示文章标题、内容和缩略图。

Firstly, obtaining the article details data is usually througharchiveDetailLabel to complete, and assign the result to a variable, for examplearticle:

{% archiveDetail article %}
    <div class="article-header">
        <h1>{{ article.Title|default:"【重要通知】本站最新动态" }}</h1>
        <p class="description">{{ article.Description|default:"本文暂无简介,敬请期待更多精彩内容!" }}</p>
    </div>

    <div class="article-image">
        <img src="{{ article.Thumb|default:"/static/images/default-thumbnail.webp" }}" alt="{{ article.Title|default:"默认图片" }}">
    </div>

    <div class="article-content">
        {% if article.Content %}
            {{ article.Content|safe }}
        {% else %}
            <p>文章内容正在创作中,请稍后访问。</p>
        {% endif %}
    </div>
{% endarchiveDetail %}

In this example:

  • Article titlearticle.Titleand descriptionarticle.Descriptiondirectly useddefaultfilter, when they are empty, it will display the specified default text.
  • Article Thumbnailarticle.ThumbAlso useddefaultFilter, when the image path is empty, it will load a preset default image to avoid broken images on the page.
  • Article Contentarticle.ContentDue to the possibility of containing complex HTML structures, here useiftags to determine if they exist. If they exist, then through|safeThe filter outputs safely; if it does not exist, it displays a friendly prompt.

Through these methods, no matter how the data in the backend content management system changes, our front-end page can maintain good display effects and provide users with a smooth and professional browsing experience.


Common Questions (FAQ)

1. How to determine if a list (such as a related articles list) is empty, and display 'No content' when it is empty?Safe CMS template engineforloop tag built-inemptyClauses, specifically used to handle the case where the list is empty. You do not need to use it extra.ifJudgment:

{% archiveList relatedArchives with type="related" limit="5" %}
    {% for item in relatedArchives %}
        <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
    {% empty %}
        <li>暂无相关内容。</li>
    {% endfor %}
{% endarchiveList %}

2. If there is a variable for some image link (such asarchive.LogoThe image may not exist, how to avoid displaying broken images in the template and provide a default image?The simplest method is to usedefaultfilters.srcApply the filter directly in the property, specify the path to a default image.

<img src="{{ archive.Logo|default:"/public/static/images/default_logo.png" }}" alt="{{ archive.Title|default:"网站Logo" }}">

Make sure that/public/static/images/default_logo.pngis the real default image path existing on your website.

3. Besides simple default text, can I display a more complex HTML structure when the variable is empty?Of course you can. In this case, combiningifTags andelseBlock can be implemented. You can write any HTML code inelsea block, even HTML code canincludea predefined template snippet.

{% if archive.CustomAdHtml %}
    <div class="custom-ad-area">
        {{ archive.CustomAdHtml|safe }}
    </div>
{% else %}
    <div class="default-ad-placeholder">
        <p>广告位招租中...</p>
        <a href="/contact-us">了解详情</a>
    </div>
{% endif %}