In website operation, we often need to make the page more intelligent and interactive.AnQiCMS 作为一个高效且灵活的内容管理系统,不仅提供了强大的内容组织和展示能力,也允许我们在模板中巧妙地集成动态逻辑,例如通过生成 JavaScript 代码片段来实现更复杂的功能。

AnQiCMS's template engine syntax is similar to Django, which provides great convenience for us to dynamically handle data.It is developed based on Go language, runs fast, and can stably support various content management needs.{{变量}}Get the data passed by the backend and process it through{% 标签 %}to control the page logic.

Why do you need to dynamically generate JavaScript code snippets in the AnQiCMS template?

Dynamically generate JavaScript code snippets, meaning that we can execute different JS logic on the front-end based on different data or page states passed from the backend. This is very useful in many scenarios:

  1. Personalized Data Tracking and Statistics:When the user browses a specific article or product page, you may need to send the article's ID, title, category, and other information to third-party statistical tools (such as Google Analytics, Baidu Statistics).This information is usually stored on the backend of AnQiCMS, and it can be accurately passed to the statistics script through dynamic JS.
  2. Initialization of Interactive Components:Some frontend libraries or components (such as carousels, charts, map plugins) require data provided by the backend during initialization.We can directly inject this data into the JS code, so that the component can obtain the correct information when it loads.
  3. Conditional Front-end Logic:
  4. SEO Optimization and Structured Data:Although AnQiCMS provides:jsonLdLabels can be used to generate structured data, but in some specific cases, you may need to dynamically build or modify these data through JavaScript to meet more complex SEO strategies.

In AnQiCMS template, the core method for dynamically generating JavaScript

The most direct method to dynamically generate JavaScript in a template is to embed the AnQiCMS variable directly into<script>Label inside. The key is that we need to ensure that these variables can be correctly identified and used by JavaScript.

First, we write in the template<script>Labels, just like writing ordinary HTML. Then, insert AnQiCMS variables into it.

For example, if we want to get the current page's article ID and title on the front end:

<script>
    // 假设我们已经通过 AnQiCMS 标签获取了文章的 ID 和标题
    // {% archiveDetail pageId with name="Id" %}
    // {% archiveDetail pageTitle with name="Title" %}

    // 动态生成 JavaScript 变量
    let articleId = {{ pageId }};
    let articleTitle = '{{ pageTitle }}';

    console.log('当前文章 ID:', articleId);
    console.log('当前文章标题:', articleTitle);
</script>

Please note that for string type variables (such aspageTitle),我们需要用单引号或双引号将其包裹起来,以符合 JavaScript 的语法规范。数字类型则可以直接输出。

UseaddFilter concatenation variable

When we need to combine multiple variables or fixed strings into a complete JavaScript string,addThe filter is very convenient.addThe role of the filter is to connect two values, whether it is adding numbers or concatenating strings, it can handle it.

In AnQiCMS templates,addThe way to use the filter is{{ obj|add:obj2 }}.

For example, if we want to concatenate a log message containing the article ID and title:

<script>
    // 假设我们已经获取了文章的 ID 和标题
    // {% archiveDetail pageId with name="Id" %}
    // {% archiveDetail pageTitle with name="Title" %}

    let articleId = {{ pageId }};
    let articleTitle = '{{ pageTitle }}';

    // 使用 add 过滤器拼接字符串和变量
    let logMessage = '文章 ID 为 ' + {{ pageId|add:""|safe }} + ',标题为 "' + '{{ pageTitle|add:""|safe }}' + '"。';

    console.log(logMessage);
</script>

It should be especially noted that:|add:""|safeThis part:

  • |add:""This operation will force the previous variable to be converted to a string type.Although JavaScript itself has implicit conversion when concatenating, explicitly converting at the template layer can avoid some potential issues and ensure that pure string content is output to JS.For numbers, this will convert it to a numeric string.
  • |safe:This filter is crucial!AnQiCMS's template engine defaults to HTML-encoding all output content to prevent cross-site scripting attacks (XSS). This means that like<script>Labels, quotes, and other special characters will be converted to&lt;script&gt;/&quot;entity characters. If you do not use dynamic-generated JavaScript code|safeFilter, then the browser will not recognize these escaped codes, but will only display them as plain text on the page.|safeTell the template engine that this part of the content is safe and does not need to be escaped, and the original HTML/JS content can be output directly.

Case Analysis in Practice

Let's take a look at some combined examples.addfilters and|safeActual examples of filters generating dynamic JavaScript.

Case 1: Dynamically setting statistical event parameters.

The translation of 'auto' to 'English' is 'English': 假设你需要向第三方事件追踪服务发送当前页面的详细信息:

{% archiveDetail articleId with name="Id" %}
{% archiveDetail articleTitle with name="Title" %}
{% archiveDetail categoryObj with name="Category" %}
{% archiveDetail categoryName with name="Title" id=categoryObj.Id %} {# 获取分类名称 #}

<script>
    // 定义事件数据对象
    let eventData = {
        'page_id': {{ articleId|add:""|safe }},
        'page_title': '{{ articleTitle|add:""|safe }}',
        'category_name': '{{ categoryName|add:""|safe }}',
        'event_time': new Date().toISOString()
    };

    // 假设你的第三方服务有一个 trackEvent 方法
    if (typeof myAnalyticsService !== 'undefined') {
        myAnalyticsService.trackEvent('page_view', eventData);
        console.log('事件已追踪:', eventData);
    } else {
        console.warn('myAnalyticsService 未定义,无法追踪事件。');
    }
</script>

In this example, we usearchiveDetail标签获取了文章 ID、标题和分类名称,并通过|add:""|safeInject them safely into the JavaScript object.

Case two: Load different scripts based on the content model type.

AnQiCMS supports flexible content models. You may want to load different interaction scripts for the article model and product model pages.

{% archiveDetail moduleId with name="ModuleId" %} {# 获取当前文档的模型ID #}

<script>
    let currentModuleId = {{ moduleId|add:""|safe }};

    if (currentModuleId === 1) { // 假设模型ID 1 是文章模型
        console.log('加载文章页特有的脚本...');
        // loadArticleSpecificScript();
    } else if (currentModuleId === 2) { // 假设模型ID 2 是产品模型
        console.log('加载产品页特有的脚本...');
        // loadProductSpecificScript();
    } else {
        console.log('未知模型类型,不加载特定脚本。');
    }
</script>

Here, we utilizemoduleIdDetermine the model type of the current page and then execute different actions