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:
- 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.
- 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.
- 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.
- SEO optimization and structured data:Although AnQiCMS provides
jsonLdLabel 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<script>/"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