How to determine whether to remove HTML tags in AnQiCMS templates based on conditions?

In the development and maintenance of website templates, we often encounter such needs: to decide whether a certain HTML element on the page is displayed based on specific data conditions.For example, an article only displays the image tag when there is a thumbnail or when a custom field has content, and renders the corresponding block.This 'display on demand' mechanism not only makes the template code cleaner, avoids the appearance of empty tags or unnecessary visual elements on the page, but also significantly improves the user experience and page loading efficiency.

AnQiCMS uses a template engine that is similar to the Django template engine, providing powerful and flexible conditional judgment and loop control capabilities, allowing us to easily implement these dynamic display logic.Understanding and making good use of these features is the key to building efficient and elegant AnQiCMS website templates.

Use conditional judgment tags (if)Precise control of HTML display

AnQiCMS template, the most basic and core condition control tool isifLabel. Through it, we can determine whether to retain or discard an HTML block based on the existence of variables, specific values, or comparisons between variables.

ifThe basic syntax of the tag is{% if 条件 %} ... {% endif %}when the condition is true (true),{% if %}and{% endif %}The content between will be rendered; otherwise, this part of the content will be ignored.

For example, on the article detail page, we usually want to display the thumbnail only when there is a thumbnail of the article.<img>Label, to avoid broken icons or blank placeholders when images are missing. This can be achieved in the following way:

{% if archive.Thumb %}
    <img src="{{archive.Thumb}}" alt="{{archive.Title}}" class="article-thumbnail">
{% endif %}

Here,archive.ThumbRepresents the thumbnail path of the article. If this variable has a value (i.e., the thumbnail exists),<img>the tag will be rendered.

besides the simple existence judgment,ifThe label supports more complex logic:

  • Multi-branch judgment:Use{% elif 条件 %}and{% else %}Can handle various situations. For example, display different prompts based on the article status:

    {% if archive.Status == 1 %}
        <span class="status-published">已发布</span>
    {% elif archive.Status == 0 %}
        <span class="status-draft">草稿</span>
    {% else %}
        <span class="status-unknown">状态未知</span>
    {% endif %}
    
  • Variable comparison:Can compare the value of variables, for example, to determine whether a certain ID is a specific value:{% if archive.Id == 10 %}.

  • Logic combination:Useand/or/notPerform logical combination to build more refined judgment conditions. For example, only display when the article has a description and the length of the description is greater than a certain value:

    {% if archive.Description and archive.Description|length > 20 %}
        <p class="article-summary">{{archive.Description}}</p>
    {% endif %}
    

    This also useslengthFilter used to get the length of a string, which is very practical when determining if the content is sufficient to display.

Dynamic display in loops and handling of empty lists (forandempty)

When we need to traverse list data (such as article list, category list),forloop is indispensable. AnQiCMS'sforThe label not only supports regular iteration, but also providesemptya sub-label for handling the special case when the list is empty.

The syntax structure is{% for item in 列表 %} ... {% empty %} ... {% endfor %}.

If列表there is data,{% for %}and{% empty %}The content between will be rendered repeatedly; if列表The content inside the loop will not be rendered, instead, the content of the block will be displayed.{% empty %}and{% endfor %}This content will be rendered once. This makes it possible to display friendly prompt information when there is no data, avoiding the appearance of blank pages or chaotic structures.

For example, in an exhibition area for products, if there are no products under the current category, we can display a prompt such as 'No products available':

<div class="product-list">
    {% archiveList products with moduleId="2" categoryId=currentCategory.Id limit="8" %}
        {% for item in products %}
            <div class="product-item">
                <h3><a href="{{item.Link}}">{{item.Title}}</a></h3>
                {% if item.Thumb %}
                    <img src="{{item.Thumb}}" alt="{{item.Title}}">
                {% endif %}
            </div>
        {% empty %}
            <p class="no-products-tip">当前分类暂无产品,敬请期待!</p>
        {% endfor %}
    {% endarchiveList %}
</div>

We can also continue to use it inside the loopifLabel to identify each list item (item) based on the attribute for conditional judgment, for example, judgment in the above example whether it exists to display the image.item.ThumbOptimize template output: remove extra blank lines.

Optimize template output: remove extra blank lines.

When using conditional judgment and loop tags, the template engine may introduce some unnecessary blank lines during rendering, especially between logical tags and HTML tags.This does not affect the page functionality, but it may make the generated HTML source code look less 'clean'.{%-and-%}Such special markers are used to remove these blank spaces during rendering.

  • {%-: will remove all spaces to the left of the tag (including newline characters).
  • -%}English will remove all whitespace to the right of the label (including newline characters).

For example, if aifThere are extra blank lines before and after the statement:

{# 原始代码,可能产生空白行 #}
<div>
    {% if archive.Thumb %}
        <img src="{{archive.Thumb}}">
    {% endif %}
</div>

{# 优化后,减少空白行 #}
<div>
{%- if archive.Thumb %}
    <img src="{{archive.Thumb}}">
{%- endif %}
</div>

By adding-Symbols, can effectively control the number of blank lines in the generated HTML, making the code more compact.

Data preprocessing and default value strategy

Sometimes, we do not want to completely remove HTML tags, but rather provide a default value when data is missing, to prevent the direct output of empty variables from causing the page display to be unattractive