HTML encoding utilities for secure output rendering with configurable encoding rules and options to prevent XSS attacks and ensure safe template output.
Generates HTML encoding functions with configurable encoding behavior for security and output control.
/**
* Generate HTML encoding function
* @param {boolean} doNotSkipEncoded - Whether to encode already encoded entities
* @returns {function} HTML encoding function that encodes unsafe characters
*/
function encodeHTMLSource(doNotSkipEncoded);Usage Examples:
const doT = require("dot");
// Create encoding function
const encode = doT.encodeHTMLSource(false);
const result = encode("<script>alert('xss')</script>");
// Output: "<script>alert('xss')</script>"
// Encoding with doNotSkipEncoded=true
const strictEncode = doT.encodeHTMLSource(true);
const strictResult = strictEncode("& already encoded");
// Output: "&amp; already encoded" (re-encodes &)
// Default encoding (doNotSkipEncoded=false)
const defaultEncode = doT.encodeHTMLSource(false);
const defaultResult = defaultEncode("& already encoded");
// Output: "& already encoded" (preserves &)The HTML encoding function replaces dangerous characters with their HTML entity equivalents.
// Default encoding rules
const encodeHTMLRules = {
"&": "&", // Ampersand
"<": "<", // Less than
">": ">", // Greater than
'"': """, // Double quote
"'": "'", // Single quote
"/": "/" // Forward slash
};
// Pattern matching (when doNotSkipEncoded=false)
const matchHTML = /&(?!#?\w+;)|<|>|"|'|\//g;
// Pattern matching (when doNotSkipEncoded=true)
const matchHTMLStrict = /[&<>"'\/]/g;Character Encoding Examples:
const doT = require("dot");
const encode = doT.encodeHTMLSource(false);
// Individual character encoding
console.log(encode("&")); // "&"
console.log(encode("<")); // "<"
console.log(encode(">")); // ">"
console.log(encode('"')); // """
console.log(encode("'")); // "'"
console.log(encode("/")); // "/"
// Complex string encoding
const html = '<div class="test" data-value=\'42\'>Hello & Goodbye</div>';
const encoded = encode(html);
// Output: "<div class="test" data-value='42'>Hello & Goodbye</div>"HTML encoding is automatically integrated into template compilation when using the {{!variable}} syntax.
// Automatic encoding in templates
// {{!variable}} syntax uses doT.encodeHTMLSource internally
// Template compilation with encoding
const needsEncoding = /\{\{!([\s\S]+?)\}\}/g.test(templateString);
if (needsEncoding) {
// Encoding function is automatically included in compiled template
}Template Usage Examples:
const doT = require("dot");
// Template with encoded output
const template = doT.template(`
<div class="content">
<h1>{{!it.title}}</h1>
<p>{{!it.description}}</p>
<div class="html-content">{{!it.htmlContent}}</div>
</div>
`);
const result = template({
title: "Blog Post <script>",
description: "This & that \"article\"",
htmlContent: "<em>Emphasized</em> & <strong>strong</strong>"
});
// Output (formatted for readability):
// <div class="content">
// <h1>Blog Post <script></h1>
// <p>This & that "article"</p>
// <div class="html-content"><em>Emphasized</em> & <strong>strong</strong></div>
// </div>Configure encoding behavior through template settings and global variables.
// Template settings for encoding control
const templateSettings = {
doNotSkipEncoded: boolean, // Re-encode already encoded entities
selfcontained: boolean // Include encoding function in compiled template
};
// Global encoding function availability
if (typeof _encodeHTML !== 'undefined') {
// Use global encoding function
} else {
// Generate local encoding function
}Configuration Examples:
const doT = require("dot");
// Configure global encoding behavior
doT.templateSettings.doNotSkipEncoded = true;
// Template with strict encoding
const strictTemplate = doT.template("Value: {{!it.value}}");
const strictResult = strictTemplate({ value: "<test>" });
// Output: "Value: &lt;test&gt;" (re-encodes existing entities)
// Self-contained template with encoding
const selfContainedTemplate = doT.template(
"Content: {{!it.content}}",
{ selfcontained: true }
);
// Encoding function is embedded in the compiled template
// Custom encoding settings per template
const customTemplate = doT.template(
"Message: {{!it.message}}",
{ doNotSkipEncoded: false }
);
const customResult = customTemplate({ message: "& encoded" });
// Output: "Message: & encoded" (preserves existing encoding)Proper HTML encoding is crucial for preventing XSS attacks and ensuring safe output.
const doT = require("dot");
// SECURE: Use {{!variable}} for user input
const secureTemplate = doT.template(`
<div class="user-comment">
<strong>{{!it.username}}</strong>: {{!it.comment}}
</div>
`);
// DANGEROUS: Using {{=variable}} for user input (DON'T DO THIS)
const dangerousTemplate = doT.template(`
<div class="user-comment">
<strong>{{=it.username}}</strong>: {{=it.comment}}
</div>
`);
// Safe rendering of user input
const safeResult = secureTemplate({
username: "<script>alert('xss')</script>",
comment: "This is a comment with <strong>HTML</strong>"
});
// Output: Safely encoded, no script execution
// When to use unencoded output ({{=variable}})
const trustedTemplate = doT.template(`
<div class="admin-content">
{{=it.trustedHtmlContent}} <!-- Only for trusted, pre-sanitized content -->
</div>
`);doNotSkipEncoded: false is more performant as it skips already-encoded entities{{=variable}} only for trusted content to avoid unnecessary encoding overhead