How to dynamically generate JavaScript code snippets in AnQiCMS templates and use the `add` filter to concatenate variables?

Calendar 👁️ 55

In website operation, we often need to make the page more intelligent and interactive.AnQiCMS as an efficient and flexible content management system not only provides powerful content organization and display capabilities but also allows us to cleverly integrate dynamic logic in templates, such as by generating JavaScript code snippets to implement more complex functions.

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.In the template, we can use{{变量}}To get the data passed from the backend and 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, which means we can execute different JS logic on the front-end based on different data or page states from the backend. This is very useful in many scenarios:

  1. Personalized data tracking and statistics:When a 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 can be accurately passed to the statistics script through dynamic JS.
  2. Initialization of interactive components:Some frontend libraries or components (such as sliders, 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 frontend logic:Based on the publication status of the article, user permissions, or specific tags, we may need to display or hide certain elements, or trigger specific animation effects.By judging these conditions in the template and generating the corresponding JS, a highly customized user experience can be achieved.
  4. SEO optimization and structured data:Although AnQiCMS providesjsonLdLabel 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.

The core method for dynamically generating JavaScript in the AnQiCMS template

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

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

For example, if we want to get the article ID and title of the current page 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 variables (such aspageTitleWe need to enclose the number with single or double quotes to comply with JavaScript syntax rules. Numeric types can be output directly.

UseaddFilter concatenation variable

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

In the AnQiCMS template,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 particularly noted that|add:""|safeThis part:

  • |add:""This operation will force the preceding variable to be converted to a string type.Although JavaScript itself has implicit conversion when concatenating, it is better to convert explicitly at the template level to avoid potential problems 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 escaping all output content to prevent cross-site scripting attacks (XSS). This means that like<script>Special characters such as tags, quotes, and others will be converted to&lt;script&gt;/&quot;entity characters. If you do not use the dynamically generated JavaScript code correctly.|safeIf a filter is applied, the browser will not recognize these escaped codes and will only display them as plain text on the page.|safeTell the template engine that this part of the content is safe, no escaping is needed, and the original HTML/JS content can be output directly.

Case study analysis

Let's take a look at several combinationsaddFilters and|safeFilter generates real examples of dynamic JavaScript

Case one: Dynamically set statistical event parameters

Assume you need to send the current page details to a third-party event tracking service:

{% 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 usearchiveDetailThe tag retrieved the article ID, title, and category name, and through|add:""|safeInject them safely into JavaScript objects.

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 article models and product models.

{% 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>

We use here,moduleIdDetermine the model type of the current page and then execute different

Related articles

Can the `add` filter be used to generate dynamic HTML attributes, such as the value of `data-` attributes?

In modern web development, dynamically generating HTML attributes, especially `data-` attributes, has become a common requirement.These properties not only provide additional data support for front-end JavaScript, but also enhance the presentation of elements without affecting the page semantics.AnQiCMS as a content management system that focuses on flexibility, its powerful template engine naturally also provides the possibility to meet this need.So, can the `add` filter in the AnQiCMS template handle the task of dynamically generating `data-` attribute values?

2025-11-07

How to use the `add` filter to dynamically add additional descriptions to the field in the AnQiCMS backend user group management (`userGroupDetail`)?

In the AnQiCMS management background, the user group management (`userGroupDetail`) module is the basis for us to divide permissions, set levels for different user groups, and even configure VIP services.Generally, each user group has its core attributes, such as name, level, price, etc., which are directly displayed on the back-end interface for convenient daily management.However, sometimes we hope that these fields are not just cold data, but can also have some additional, more descriptive information. For example

2025-11-07

How to pass the `add` filter as a parameter to the `macro` macro function and perform internal text processing?

In AnQi CMS daily content operation, we pursue efficient and flexible management and display of website content.The template system is the core of achieving this goal, among which the `macro` macro function and the `add` filter are two very practical tools.Understand how they work together, especially how to use the `add` filter for internal text processing in macro functions, which can greatly enhance the reusability and dynamism of our templates.The AnQi CMS template system uses syntax similar to Django, which allows us familiar with Web development to quickly get started.

2025-11-07

When it comes to concatenating a large number of strings, which filter, `add` or `join`, performs better?

In AnQi CMS template development, we often need to combine different text fragments into a complete string to meet the display requirements of the page.AnQi CMS provides various template filters to complete this task, among which the `add` and `join` filters are two commonly used string concatenation tools.However, when faced with the need to concatenate a large number of strings, choosing the right tool becomes particularly important, as this directly affects the speed of page rendering and user experience.###

2025-11-07

How does the `add` filter handle the addition/pasting operation with boolean values `true` and `false` as well as numbers or strings?

In Anqi CMS template development, we often need to process and display data.Among them, the `add` filter is a very practical tool that allows us to add numbers and concatenate strings.However, when the boolean values `true` and `false` are involved in these operations, their behavior may puzzle some users who are new to the subject.Today, let's take a deep dive into how the `add` filter handles addition or concatenation operations with boolean values, numbers, or strings.

2025-11-07

How to use the `add` filter to dynamically add a uniform prefix or suffix to the single page titles in the `pageList`?

In Anqi CMS, content management is not limited to the backend's add, delete, modify, and query, but also manifests in the flexibility and diversity of front-end display.In the face of common single-page websites (such as "About Us", "Contact Us", etc.), sometimes we hope that they can be unified with specific identifiers when displayed in lists or navigation, such as If you modify the background title one by one, it is not only inefficient but also lacks uniformity and maintainability.At this time, utilizing the powerful template engine function of AnqiCMS, with the clever filter

2025-11-07

How to combine other filters with the `add` filter to ensure safe concatenation and prevent XSS attacks when processing user input?

In AnQi CMS, managing website content involves entering a variety of information regularly.Whether it is the main text of the article, user comments, or form submissions, this user-generated content injects vitality into the website while also bringing potential security risks, the most common and severe of which is XSS (Cross-site Scripting attack).This article will discuss how the `add` filter works in processing user input content, how it协同acts with other security filters to build a strong defense line, effectively preventing XSS attacks.

2025-11-07

How to dynamically generate a link to the comment area based on `item.Id` in `archiveList`?

In AnQi CMS, in order to enhance the user experience of the website, we often hope that users can quickly find the specific content on the page.For example, when you click on the "View Comments" link next to an article title on a document list page, you can directly jump to the comments section of the article detail page.This not only saves users time, but also makes interactions more direct. Today, let's discuss how to dynamically generate anchor links to comment sections in the `archiveList` loop based on the unique identifier `item.Id`.

2025-11-07