How to remove HTML tags in AnQiCMS template based on conditions?

Calendar 👁️ 74

In the development and maintenance of website templates, we often encounter the need to determine whether a certain HTML element on a page is displayed based on specific data conditions.For example, an article will only display an image tag if there is a thumbnail, or if a custom field has content, the corresponding block will be rendered.This on-demand display mechanism not only makes the template code more organized, avoids the appearance of empty tags or unnecessary visual elements on the page, but also significantly improves user experience and page loading efficiency.

AnQiCMS uses a template engine with syntax similar to Django's, which provides powerful and flexible conditional judgment and loop control capabilities, allowing us to easily implement these dynamic display logic.Understanding and effectively using these features is the key to building a highly efficient and elegant AnQiCMS website template.

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

AnQiCMS template, the most basic and core conditional control tool isifLabel. Through it, we can decide whether to keep or remove an HTML block based on the existence of variables, specific values, or comparisons between variables.

ifThe basic syntax of tags 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 the article has one.<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,ifLabels support 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:You can compare the value of variables, for example, to determine if an ID is a specific value:{% if archive.Id == 10 %}.

  • Logical combination:Useand/or/notPerform logical combination to build finer 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 useful 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 lists, category lists),forLoops are indispensable. AnQiCMS'sforLabels not only support regular loop iteration, but also provideemptya sub-label to handle the special case of an empty list.

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

If列表with data,{% for %}and{% empty %}The content between will be rendered repeatedly; if列表It is empty,{% empty %}and{% endfor %}The content between the brackets will be rendered once. This makes it possible to display friendly prompts when there is no data, avoiding the appearance of blank or disordered pages.

For example, in a product display area, 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 using it inside the loop,ifLabel to determine each list item (item) to make conditional judgments based on its properties, such as the judgment in the above exampleitem.Thumbto display the image.

Optimize template output: remove extra blank lines

When using conditional 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 function, but may make the generated HTML source code not as 'clean'.AnQiCMS template engine provides{%-and-%}Such a special marker is used to remove these blank spaces during rendering.

  • {%-: Removes all spaces on the left side of the tag (including newline characters).
  • -%}: It will remove all whitespace to the right of the tag (including newline characters).

For example, if aifstatement has extra whitespace lines before and after:

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

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

By adding-The symbol 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 are not to remove HTML tags completely, but to provide a default value when data is missing to prevent empty variables from being output directly and causing the page display to be ugly

Related articles

What are the built-in cleanup tools of AnQiCMS when processing HTML content from external sources?

When processing HTML content collected from external sources, AnQiCMS (AnQiCMS) provides a series of built-in cleaning tools and strategies to help users efficiently manage and optimize content, ensuring the quality, safety, and display effect of website content.These features provide comprehensive support from the automated processing before the content is stored to the refined control during content display.

2025-11-08

How to use AnQiCMS filter to preliminarily sanitize the HTML content uploaded by users?

In website operation, the security and display effect of user uploaded content are crucial.Especially when users have the opportunity to submit content containing HTML tags, how to effectively perform preliminary purification, prevent malicious code injection (XSS attacks), and ensure that the content is presented as expected, is a challenge that each operator needs to face.AnQiCMS as a system focused on efficiency and security, provides us with a variety of tools to meet this need.

2025-11-08

How should I make AnQiCMS display the Markdown original text instead of rendering it as HTML?

In the daily content operation of AnQiCMS, we usually hope that the system can automatically render Markdown content into beautiful HTML for direct display on the website. However, in certain specific scenarios, such as when you may need to export the Markdown original text to other platforms, or display Markdown code blocks directly on the page (such as in tutorials or technical articles), or provide pure Markdown data for API interfaces

2025-11-08

How to ensure proper closing of tags when truncating HTML with the `truncatechars_html` filter?

In website content operation, we often need to truncate the long article content displayed on list pages, abstracts, or card views to maintain the cleanliness and consistency of the page.However, when this content contains HTML tags (such as paragraphs `<p>`, links `<a>`, bold `<strong>`, images `<img>`, etc.), simple string truncation often leads to problems: it may truncate the tags in the middle, causing the page to display incorrectly, and even destroying the entire page's HTML structure.

2025-11-08

Does AnQiCMS provide a feature to batch remove all HTML tags from all articles under a specific content model?

In website content operation, we often encounter situations where we need to uniformly process a large number of articles, such as for content standardization, SEO optimization needs, or preparing to export content to other platforms, we need to remove the HTML tags from the articles.AnQiCMS (AnQiCMS) is a powerful content management system that provides an efficient way to solve such problems.The Anqi CMS indeed has the ability to remove all HTML tags from all articles under the specified content model in bulk.

2025-11-08

How to convert Markdown to HTML in a template and then remove the tags from the generated HTML?

In the AnQiCMS template, when handling Markdown content, it is often necessary to first convert it to HTML, and then further filter or remove specific HTML tags on this basis.This is particularly useful when creating content summaries, generating plain text previews, or implementing specific layout controls.The template tags and filters provided by AnQi CMS can help us complete these operations efficiently and flexibly.

2025-11-08

Can the `striptags` filter retain images or links in HTML content, while removing only the formatting tags?

In website content operation, we often need to handle text content that contains HTML tags.Sometimes it needs to be converted to plain text, and sometimes it is desired to retain some key elements while removing redundant formats, such as images and links.AnQiCMS's template engine provides a rich set of filters to help us handle such needs, among which the `striptags` filter is a commonly used one.Then, can this `striptags` filter retain images or links in the content when removing HTML tags?in short

2025-11-08

How to remove whitespace tags from HTML without affecting content display in AnQiCMS?

Manage website content in Anqi CMS, we often pay attention to details, such as the blank tags in HTML code.These seemingly harmless empty tags can sometimes affect the rendering of the page, and even cause slight interference to search engine optimization (SEO).Although Anqi CMS does not have a direct function to "one-click clear blank HTML tags", we can cleverly utilize its powerful content management tools to achieve this goal without affecting the actual display of content.Understanding the trouble with empty tags Empty HTML tags usually refer to `<p></p>`

2025-11-08