In AnQiCMS template, how to decide whether to display the default image or placeholder based on the existence of a variable?

Calendar 👁️ 188

In AnQiCMS template development, we often encounter situations where the content may not contain images.For example, a news article may not have an illustration, or a certain product in a product list may not have uploaded the main image temporarily.In this case, if the template directly calls the image address, it may display a broken image icon or leave a jarring blank space, which undoubtedly affects the overall aesthetics and user experience of the website.

To solve this problem, AnQiCMS provides flexible template tags and filters, allowing us to intelligently decide whether to display the actual image, a preset default image, or a placeholder based on the existence of the image variable.This not only improves the visual consistency of the page, but also maintains a good user experience when the content is not perfect.

1. Useiftag for conditional judgment

The most direct and most commonly used method is to use the AnQiCMS template syntax similar to Django'sifThe tag performs conditional judgment. By determining whether the image variable contains valid content, we can output either the actual image or a default placeholder.

Assuming we are on an article detail page, we need to display the thumbnail of the article (Thumbfield). IfThumbthe field has a value, it should be displayed; if not, a preset default image should be displayed.

First, we can usearchiveDetailTag to get the thumbnail information of the current article and assign it to a temporary variable, for examplearticleThumb:

{% archiveDetail articleThumb with name="Thumb" %}

Then, we can useifTag to determine thisarticleThumbWhether the variable is empty:

{% archiveDetail articleThumb with name="Thumb" %}
{% if articleThumb %}
    <img src="{{ articleThumb }}" alt="文章缩略图">
{% else %}
    <img src="/public/static/images/default-thumb.webp" alt="默认缩略图" class="default-image">
{% endif %}

In the code above:

  • {% archiveDetail articleThumb with name="Thumb" %}Attempts to obtain the thumbnail path of the current article and assign it toarticleThumb.
  • {% if articleThumb %}the judgment.articleThumbCheck if the variable is not empty. If it has a value (i.e., the article has a thumbnail), it will executeifThe code within the block to display the actual image.
  • {% else %}block is in,articleThumbIf empty, execute and display the default image path we have预设/public/static/images/default-thumb.webp.

This method is not only applicable to the article detail pageThumbfield, but can also be applied to the category detail pageLogoorThumbas well as the single page detail pageLogoorThumbAll fields that may contain image paths.

Part two, clever use.defaultThe filter realizes a more concise writing style.

AnQiCMS templates also provide.defaultA filter that provides a fallback value when a variable is empty. This makes the judgment and default value setting of the image variable more concise.

defaultThe usage of the filter is to add it after the variable|default:''Fill in the default value you want within the quotes.

Continue using the thumbnail of the above article as an example, to usedefaultThe filter can be implemented in this way:

<img src="{{ archive.Thumb|default:'/public/static/images/default-thumb.webp' }}" alt="文章缩略图">

Herearchive.ThumbIt directly refers to the article object on the current pagearchiveofThumbfield. Ifarchive.ThumbIs empty or undefined,defaultThe filter will replace it with/public/static/images/default-thumb.webp.

This style combines conditional judgment and default value specification in a single line, making the code more concise, especially suitable for scenarios where only a simple default value is needed. AnQiCMS also providesdefault_if_noneFilter if the variable may benil(Null pointer) rather than just an empty string, it provides a more accurate default value, but when dealing with string types like image paths, defaultThe filter is usually sufficient.

3. Special cases in handling image groups (Images)

Some content models may support image groups (such as product detail page sliders),ImagesThe field usually returns an array of image paths (or what is known as a slice).In this case, we may need to determine if the image group exists, as well as whether there is at least one image in the image group.

Assume we want to display the first image of a product, if there is no image group or the image group is empty, then display a default image:

{% archiveDetail productImages with name="Images" %}
{% if productImages and productImages|length > 0 %}
    <img src="{{ productImages[0] }}" alt="产品主图">
{% else %}
    <img src="/public/static/images/default-product.webp" alt="默认产品图">
{% endif %}

Here:

  • {% archiveDetail productImages with name="Images" %}Assign the image group data toproductImages.
  • {% if productImages and productImages|length > 0 %}Made a double check: first make sureproductImagesThe variable itself exists and is not empty, next through|lengthThe filter determines whether the length of the array is greater than 0 to ensure that there is at least one image.
  • If the condition is met, display the first image in the image groupproductImages[0].
  • Otherwise, display the preset default product image.

If your image group is displayed in a loop and you want to display a placeholder when the entire image group is empty, you can handle it like this:

{% archiveDetail productImages with name="Images" %}
{% if productImages %}
    <div class="product-gallery">
    {% for imgUrl in productImages %}
        <img src="{{ imgUrl }}" alt="产品图">
    {% endfor %}
    </div>
{% else %}
    <div class="product-gallery-placeholder">
        <img src="/public/static/images/default-product-gallery.webp" alt="暂无图片">
        <p>此产品暂无图片展示。</p>
    </div>
{% endif %}

**Practice and Precautions

  1. Unified default image path:Place all default images in/public/static/images/the directory and name them consistently, for exampledefault-thumb.webp/default-logo.webpetc., for easy management and maintenance.
  2. Set meaningfulaltattribute:No matter whether the image exists or not, it should be<img>tagsaltProperty. For the default image,altThe property should specify its default nature, for example"默认缩略图"It is very important for SEO and accessibility. 3.

Related articles

How to elegantly handle null or undefined variables returned by the database in AnQiCMS templates to avoid page errors?

During the development of website templates, we often encounter a headache-inducing problem: when the data obtained from the database is empty (null) or a variable is not defined under certain circumstances, the template rendering will cause an error, resulting in the page not displaying normally and significantly reducing the user experience.AnQiCMS (AnQiCMS) is based on its powerful Go language backend and flexible Django-style template engine, providing us with various elegant solutions for handling such situations, allowing the template to run smoothly even when the data is incomplete.### One, make good use of conditional judgments: `{% if

2025-11-09

What is the difference between the `default_if_none` filter and the `default` filter in the AnQiCMS template, and when should the former be preferred?

In web template development, handling the case where variables may not exist or are empty is a common task.The AnQiCMS template system provides a variety of filters to help us elegantly handle such issues, with `default` and `default_if_none` being two commonly used tools.They both provide a default value when the variable is 'no value', but there is a subtle but important difference in the definition of 'no value'.Understanding these differences can help us control the display of template content more accurately.###

2025-11-09

How to set default display content for possibly empty variables in the `default` filter of AnQiCMS templates?

In Anqi CMS template design, we often encounter situations where variable values may be empty.For example, an article may not have a thumbnail set or a product field may be temporarily unfilled.If the template directly displays these empty values, ugly blank spaces will appear on the page, affecting user experience, and may even confuse visitors.To solve this problem, Anqi CMS provides a very practical filter mechanism, where the `default` filter is the key tool to ensure the continuity of content display.### `default` Filter

2025-11-09

How to avoid excessive nesting of `if` statements in AnQiCMS templates to improve code readability?

In AnQiCMS template development, we often encounter situations where we need to display different content based on different conditions.Newcomers may tend to use the `{% if condition %}` statement extensively. As the project requirements grow, these conditional judgments become nested layer by layer, which quickly makes the template difficult to read, maintain, and even hides potential logical errors.Code readability once reduced, not only will the development efficiency be affected, but the future feature iteration and problem troubleshooting will also become extremely difficult.Fortunate is that AnQiCMS is based on Go language Django-like

2025-11-09

In AnQiCMS template, how to judge if the list is empty and display a prompt of 'No content'?

When using AnQiCMS for website template development, you often encounter situations where you need to display list data, such as article lists, product lists, or image galleries.When we retrieve data through template tags (such as `archiveList` or `categoryList`) and use a `for` loop to iterate over the list, if the list is empty, it is usually necessary to provide the user with a friendly prompt instead of displaying a blank space.How can you elegantly judge whether a list is empty in a `for` loop and display a 'No content' prompt?

2025-11-09

How to judge if there is a thumbnail in the `archiveList` tag in AnQiCMS template through `if` to selectively display images?

In AnQiCMS template development, displaying list content is a common requirement, and how to elegantly handle the images in these lists, especially thumbnails, is directly related to the visual effects and user experience of the website.The `archiveList` tag is one of the core content call tags of AnQiCMS, which helps us flexibly obtain various document lists.However, in practice, we often encounter situations where certain documents have not set thumbnails, which may lead to broken images or layout confusion on the page. At this time

2025-11-09

How to display different content in the AnQiCMS template based on the value of the `item.Status` field (such as approved, in review)?

In website content operation, the review status of the content is a very important link.Whether it is a comment submitted by the user, a forum post, or an article or product information released by the website administrator, it often needs to be reviewed before it can be displayed to the public.AnQiCMS provides a flexible template mechanism that allows us to easily display different content on the front-end page based on the review status of the content (such as "approved" or "in review"), thereby providing users with clearer and more accurate feedback.AnQiCMS template syntax is similar to the Django template engine

2025-11-09

In AnQiCMS template, how to judge and display the 'In stock' or 'Out of stock' status based on the product inventory (`Stock`) quantity?

It is crucial to clearly communicate the inventory status of products to users in website operations, especially for sites involving product display.This not only optimizes the user experience, reduces invalid consultations, but also effectively guides the user's purchase decision.AnQiCMS as a flexible and efficient content management system, implements the display of "in stock" or "out of stock" status according to the product inventory quantity in the template, which is very intuitive. AnQiCMS template system adopts a syntax similar to Django, which allows us to control the display of page content through concise tags and variables.When processing product information

2025-11-09