How to correctly display the rich text content of AnQiCMS documents and support lazy loading of images?

As an experienced website operation expert, I am willing to delve into the strategy of rich text content display and image lazy loading in AnQiCMS.In today's increasingly rich digital content, presenting content efficiently and beautifully, while considering user experience and website performance, is a focus for every operator.AnQiCMS as an efficient CMS based on the Go language provides us with powerful tools to achieve these goals.


Elegantly display rich text content in AnQiCMS and implement image lazy loading

Content is the soul of a website, and rich text content is the body that carries these souls.In AnQiCMS, we usually write articles, product details, single-page introductions, and other content through a powerful rich text editor in the background document editing interface.This content includes various elements such as text styles, links, and images. If it cannot be displayed correctly on the front end, it will greatly affect the user experience.At the same time, as the number of media resources such as images increases, the loading speed of the website will often be affected, and at this time, the technology of image lazy loading becomes particularly important.

This article will detail how to correctly render the rich text content edited in the AnQiCMS template, and cleverly integrate the image lazy loading function, so that your website can take a step up in terms of performance and user experience.

Understand the rich text content in AnQiCMS

In the AnQiCMS document management module, whether you are creating articles, products, or single pages, the core content area corresponds to a namedContentThe field.This field stores the HTML code that you edit through the rich text editor.Contentin the field.

When we want to display this content in the front-end template, we need to obtain this through the AnQiCMS template tagsContentvalue of the field. The most commonly used isarchiveDetailThe tag that can retrieve the details of the current page or a document with a specified ID.

The core of correctly rendering rich text content: |safeFilter

AnQiCMS template engine (similar to Django template) for website security, it defaults to escaping all output variables as HTML entities. This means that if you directly output{{ archive.Content }}then<p>Will become&lt;p&gt;,<img>Will become&lt;img&gt;Wait, what the user sees is a pile of raw HTML code, not the final formatted and rendered effect.

In order for the browser to correctly parse and render this HTML content, we need to explicitly tell the template engine that this content is "safe" and does not require escaping. At this point,|safeThe filter comes into play.

You are usingarchiveDetailtag to obtainContentwhen using the field, you need to combine it with|safeuse the filter together:

{%- archiveDetail articleContent with name="Content" %}
<div class="article-content">
    {{ articleContent|safe }}
</div>

Here, we first go through{%- archiveDetail articleContent with name="Content" %}Assign the rich text content of the current document to a variable namedarticleContent(Note that you can use-to remove the empty lines occupied by tags, making the code cleaner). Then, in{{ articleContent|safe }},|safeThe filter indicates that the template engine willarticleContentThe HTML code is directly output to the page, and the browser will parse and render it as if it were ordinary HTML, ensuring that your content's layout, style, and images are presented perfectly.

About Markdown content rendering

It is worth mentioning that if your AnQiCMS backend has enabled the Markdown editor and the document content is written in Markdown format, thenContentThe field is beingarchiveDetailWhen the tag is retrieved, AnQiCMS will default to automatically converting it to HTML. You can also convert it by usingarchiveDetailthe tag withrender=trueA parameter is used to explicitly request the conversion of Markdown to HTML (even if it is already enabled by default, explicit declaration ensures consistent behavior), for example{%- archiveDetail articleContent with name="Content" render=true %}. The HTML content after conversion still needs|safea filter to ensure correct rendering.

3. Implement intelligent lazy loading of images:lazyparameters cooperate with the front-end

Images are an indispensable part of rich text content, but too many images often lead to slow page loading.The image lazy loading (Lazy Loading) technology can effectively solve this problem: it only loads the image when it enters the user's viewport, thereby significantly improving the initial loading speed and user experience of the website.

AnQiCMS provides very friendly support for lazy loading of images in rich text content, which is mainly achieved througharchiveDetaillabel'slazyParameter to achieve.

when you arearchiveDetailSet in the labellazy="data-src"(or any custom attribute name you define, such asdata-originalWhenContentthe HTML in the<img>label'ssrcattribute is replaced withdata-srcattribute, and the original image URL is assigned todata-src.

For example, the content on the back-end includes<img src="https://en.anqicms.com/uploads/image.jpg">When the template is usedlazy="data-src"After that, the HTML output to the front-end will be<img data-src="https://en.anqicms.com/uploads/image.jpg">.

However, please note:Thislazy="data-src"The parameter itself does not make the image immediately implement lazy loading. It only completes the HTML structure transformation in lazy loading technology.HTML structure transformationThis step. To achieve the real lazy loading effect, you need to integrate a lazy loading library on the front-end page.JavaScript lazy loading libraryto complete.

The working principle of a front-end lazy loading JavaScript library:

A typical JavaScript lazy loading library will traverse all elements with attributes on the pagedata-srcof (or any custom attribute) the<img>label. It listens to whether these images have entered the user's visible area (byIntersection ObserverAPI or scroll event). Once the image enters the visible area, JavaScript will copydata-srcthe value of thesrcattribute, triggering the browser to load the image.

Implementation steps:

  1. Using AnQiCMS templatelazyparameters:In your document detail template (for examplearchive/detail.htmlorproduct/detail.html), modifyarchiveDetailTags are as follows:

    {%- archiveDetail articleContent with name="Content" lazy="data-src" render=true %}
    <div class="article-content">
        {{ articleContent|safe }}
    </div>
    

    Here we used simultaneouslylazy="data-src"to transformsrcproperties, and retainedrender=trueand|safeto ensure that the content is displayed normally.

  2. Integrated front-end JavaScript lazy loading library:Before yourbase.htmltemplate file</body>tag, introduce a lightweight lazy loading JavaScript library, or write simple lazy loading logic. Here is an example of usingIntersection ObserverAn example of implementing lazy loading of APIs (no additional libraries required, supported by modern browsers natively):

    <script>
    document.addEventListener("DOMContentLoaded", function() {
        var lazyloadImages = document.querySelectorAll("img[data-src]");
        var lazyloadThrottleTimeout;
    
    
        function lazyload () {
            if(lazyloadThrottleTimeout) {
                clearTimeout(lazyloadThrottleTimeout);
            }
            lazyloadThrottleTimeout = setTimeout(function() {
                var scrollTop = window.pageYOffset;
                lazyloadImages.forEach(function(img) {
                    if(img.offsetTop < (window.innerHeight + scrollTop)) {
                        img.src = img.dataset.src;
                        img.removeAttribute('data-src');
                    }
                });
                if(lazyloadImages.length == 0) {
                    document.removeEventListener("scroll", lazyload);
                    window.removeEventListener("resize", lazyload);
                    window.removeEventListener("orientationChange", lazyload);
                }
            }, 20);
        }
    
    
        // 使用 Intersection Observer API (推荐)
        if ("IntersectionObserver" in window) {
            let lazyloadObserver = new IntersectionObserver(function(entries, observer) {
                entries.forEach(function(entry) {
                    if (entry.isIntersecting) {
                        let img = entry.target;
                        img.src = img.dataset.src;
                        img.removeAttribute('data-src');
                        lazyloadObserver.unobserve(img);
                    }
                });
            });
    
    
            lazyloadImages.forEach(function(img) {
                lazyloadObserver.observe(img);
            });
        } else {
            // Fallback for older browsers
            document.addEventListener("scroll", lazyload);
            window.addEventListener("resize", lazyload);
            window.addEventListener("orientationChange", lazyload);
        }
    });
    </script>
    

    Add the above JavaScript code to yourbase.htmlIn the file, it can enable the lazy loading effect of images on the page. If you use an existing lazy loading library such asvanilla-lazyloadorlozad.jsyou can configure it according to its documentation.

Four, Summary and **Practice

By following these steps, your AnQiCMS website will be able to:

  1. Perfectly display rich text content:Ensure that the HTML content edited on the backend (including HTML converted from Markdown) renders correctly on the front-end page, maintaining the original formatting and styles.
  2. Implement efficient image lazy loading:Optimize image loading strategies, reduce page initial loading time, enhance user experience, especially for pages with a large number of images, the effect is significant.

As a website operation expert, I recommend that you always adhere to the following principles in content operation:

  • Content is king, experience is paramount:Ensure the accuracy, readability, and aesthetics of the content, while paying attention to the loading speed and response capability of the website.
  • Safety cannot be ignored:Though|safeThe filter can render HTML, but it also means you need to ensure the safety of the back-end content source, to avoid XSS (cross-site scripting attack) risks.
  • Continuous optimization:Regularly check the website performance report and adjust and optimize the image compression strategy, lazy loading threshold, etc. based on data feedback.

AnQiCMS provides powerful basic functions, combined with some front-end technologies and **practice, you will be able to create a professional and efficient website.


common