How to use the `escapejs` filter to safely embed template variables into JavaScript code?

Calendar 👁️ 79

In the daily use of Anqi CMS, we often need to display the content of background management, such as article titles, user comments, or other dynamic data, on the front-end page.This content is not just plain text, it also needs to be used in JavaScript code, such as variable values, function parameters, or dynamically generated HTML fragments.However, embedding template variables directly into JavaScript code, if not handled properly, may introduce a significant security vulnerability - cross-site scripting (XSS).

AnQi CMS as a corporate-level content management system that emphasizes security and efficiency, is built with a powerful template engine and provides a series of filters to help us safely process data. Among them,escapejsThe filter is specifically designed to solve XSS problems in JavaScript.

Why is it necessary to embed JavaScript code securely?

Imagine if your website had a comment section where users could submit comments. If a malicious user submitted a comment containing JavaScript code, for example<script>alert('您的Cookie被盗!')</script>And you directly embed this comment content into the JavaScript variable:

<script>
    var comment = "{{ user_comment }}"; // 假设 user_comment 是恶意评论
    // ... 后续代码使用 comment 变量
</script>

When the page loads, this malicious JavaScript code will be executed by the browser, resulting in an XSS attack.An attacker may steal the user's session information (Cookie), modify page content, or even redirect the user to a phishing website.

AnQi CMS understands the importance of data security, and therefore provides in the template design:escapejsSuch tools help us avoid such problems.

escapejsThe principle of the filter.

escapejsA filter is like a 'purifier' that can convert special characters in a string, such as single quotes, double quotes, backslashes, newline characters, etc., to JavaScript-safe\uxxxxEncoding form. Through this transformation, characters that might have been interpreted as part of the JavaScript code structure become ordinary string content, thereby losing the ability to execute malicious code.

To be specific,escapejsIt will convert all characters except letters (a-zA-Z), numbers, spaces, and slashes (/) into\uxxxxA Unicode escape sequence. This way, no matter what the original string contains, it will ultimately become a pure string literal that will not be misinterpreted as JavaScript code by the browser.

How to use it in Anqi CMS templateescapejs?

Using in Anqi CMS, a Django-like template engine,escapejsThe filter is very intuitive. You just need to embed the template variables you need in JavaScript, through the pipe character|withescapejsand connect them.

For example, let's say you have an article title variablearchive.TitleYou want to assign it to a JavaScript variable:

<script>
    // 未使用 escapejs,存在安全隐患
    // var articleTitleUnsafe = "{{ archive.Title }}"; 

    // 使用 escapejs 确保安全
    var articleTitle = "{{ archive.Title|escapejs }}";
    console.log(articleTitle); // 这将安全地打印文章标题
</script>

Ifarchive.Titlehas a value ofIt's an "interesting" articleThen if it is not usedescapejsThe JavaScript code might become:

var articleTitleUnsafe = "It's an "interesting" article"; // 语法错误,甚至可能注入代码

And if it is usedescapejsAfter, it will safely convert to:

var articleTitle = "It\u0027s an \u0022interesting\u0022 article"; // 安全,且是有效的JavaScript字符串

This string, no matter how complex or how many special characters it contains, can be correctly parsed as a normal string in JavaScript, it will not destroy the syntax structure of JavaScript, nor will it execute any potential malicious code.

You can also useescapejsFor more complex scenarios, such as passing dynamic content as parameters to JavaScript functions:

<script>
    function displayContent(title, content) {
        alert("标题:" + title);
        // 这里 content 变量可能包含HTML,后续在DOM中插入时仍需注意上下文
        document.getElementById('article-area').innerHTML = content; 
    }

    // 假设 archive 是当前文档对象
    var safeTitle = "{{ archive.Title|escapejs }}";
    var safeContent = "{{ archive.Content|escapejs }}"; // 注意:这里仅是使其成为安全的JS字符串,而非安全的HTML
    
    displayContent(safeTitle, safeContent);
</script>

<div id="article-area"></div>

In this example,archive.ContentMay contain HTML tags.escapejsWill ensuresafeContentIn JavaScript code it is a safe string literal. But when JavaScript assigns it toinnerHTMLWhen, the browser will interpret it as HTML. Ifarchive.Contentitself contains malicious HTML or JS, it may still trigger XSS in this case.So,escapejsResolved the issue of template variables embedded in JS, but if the content of the JS variable will eventually be inserted into the DOM as HTML, then the JS code itself also needs to ensure that the content is safe, or only inserted into text nodes.

Summary

In the Aiqi CMS, make use ofescapejsThe filter is a critical step to ensure that dynamic data is safely embedded in JavaScript code. It converts potential dangerous characters to safe\uxxxxEncoding effectively prevents cross-site scripting attacks (XSS), thereby ensuring the security of your website's users and data integrity. Always remember to place template variables in<script>When a JavaScript string literal is enclosed in tags, it should be used with `

Related articles

What risks should be noted when using the `safe` filter to prevent XSS attacks in AnQiCMS templates?

AanQi CMS has always paid great attention to security from the very beginning, which is fully reflected in its concise and efficient Go language architecture, aiming to provide users with a secure and stable content management environment.In the daily content publishing and template creation, we often come across various template tags and filters.Among them, the `safe` filter is a powerful tool but also one that requires our special vigilance.It allows us to output raw HTML content in the template, but it is precisely this 'freedom' that hides some risks that should not be overlooked, especially in preventing cross-site scripting (XSS) attacks.

2025-11-08

How to repeat a string a specified number of times, for example, to display a welcome message repeatedly?

In website content operations, we often encounter situations where we need to repeat certain information, such as repeating copyright information in the footer, playing a greeting phrase in the welcome area repeatedly, or adding visual separators between list items.Copying and pasting manually is not only inefficient but also very麻烦 when it needs to be modified.Luckyly, AnQiCMS's powerful template engine provides a simple and efficient way to solve this problem, one very practical feature is the `repeat` filter.###

2025-11-08

The `stringformat` filter provides which advanced string formatting options (such as number precision, alignment style)?

In the powerful template system of AnQi CMS, we often need to present dynamic data on the website, and the way data is displayed directly affects user experience and the efficiency of information communication.To present numbers, text, and other content in a more professional and clear manner, AnQi CMS provides the `stringformat` filter, which is a multifunctional formatting tool that helps us finely control the display details of content.The `stringformat` filter plays a role in AnQi CMS similar to the `fmt` in Go language

2025-11-08

How to use the `slice` filter to extract a specified range of characters or elements from a string or array?

In the process of creating AnQiCMS templates, it is essential to be able to flexibly handle strings and arrays.Whether it is to display the article summary or to extract part of the elements from the list, the `slice` filter can provide powerful and convenient help.It allows you to extract specific ranges of characters from strings or select elements from arrays at specified positions, making content display more accurate and diverse.What is the `slice` filter?In simple terms, the `slice` filter is like a precise pair of scissors

2025-11-08

How do the `center`, `ljust`, and `rjust` filters control the alignment of a string within a specified width?

In website content management, we often need to present text in an orderly and beautiful manner, especially when dealing with specific layouts or content that requires structured display.AnQiCMS's template engine provides several very practical string filters, specifically used to control the alignment of text within a fixed width. They are `center`, `ljust`, and `rjust`.Understand and make good use of them, which can help us control the display effect of the front-end page more finely.### Center the string with `center`

2025-11-08

How to check variable data type and structure for debugging in AnQiCMS template?

During AnQiCMS template development, we often encounter a frustrating scenario: the page display does not meet expectations, and the data of some variables cannot be output correctly.At this time, we urgently need a 'fire-eyed golden eyes' to see through the real data type and internal structure of the template variables.AnQiCMS's powerful Django-like template engine is flexible, but if you cannot clearly understand the 'true face' of variables during debugging, the efficiency will be greatly reduced.Luckyly, AnQiCMS provides us with a series of practical tools

2025-11-08

How to implement unified and efficient display of content for multiple sites in AnQiCMS?

AnQiCMS (AnQiCMS) is a content management system tailored for small and medium-sized enterprises and content operation teams, one of its core highlights being excellent support for multiple sites.Under the increasingly prevalent trend of multi-brand and multi-channel operation, how to efficiently manage and display the content of multiple websites on a single platform has become a focus of many users.The Anqi CMS is built around this need, creating a flexible and powerful solution to ensure the consistency of content display and operational efficiency.### Core Pillar

2025-11-08

How to customize the content model to meet the needs of personalized content display?

Today, with the increasing refinement of content operation, we often find that relying solely on traditional 'article' and 'product' categories is no longer sufficient to meet the diverse content display needs of websites.Each business scenario has its unique attributes and information structure. How to make the website's content management system (CMS) like a considerate tailor, tailoring "garments" for each type of content, is exactly what we strive for.The flexible content model feature provided by AnQiCMS (AnQiCMS) just helps us achieve this vision.Why do we need a custom content model?Imagine

2025-11-08