Embedded JavaScript templates for generating HTML markup with plain JavaScript.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Advanced template handling through the Template class for fine-grained control over the compilation process.
Creates a new Template instance for advanced template compilation control.
/**
* EJS template class for advanced template compilation
* @param text - Template text string
* @param opts - Template options object
*/
class Template {
constructor(text, opts);
}Usage Examples:
const ejs = require("ejs");
// Create template instance
const template = new ejs.Template("<h1><%= title %></h1>", {
filename: "greeting.ejs",
compileDebug: true
});
// Compile to function
const compiledFn = template.compile();
// Use the compiled function
const html = compiledFn({ title: "Hello World" });The Template class provides several methods for different stages of compilation:
/**
* Compile the template and return a template function
* @returns Template function that can be executed with data
*/
compile();
/**
* Generate the JavaScript source code for the template
* Sets this.source property with the generated code
*/
generateSource();
/**
* Parse the template text into an array of tokens
* @returns Array of template tokens (strings and EJS tags)
*/
parseTemplateText();
/**
* Process a single line of template text
* @param line - Template line to process
*/
scanLine(line);
/**
* Create the regular expression for parsing template delimiters
* @returns RegExp object for parsing template tags
*/
createRegex();Template instances have several properties that control compilation:
class Template {
/** Original template text */
templateText: string;
/** Current parsing mode */
mode: string | null;
/** Whether to truncate whitespace */
truncate: boolean;
/** Current line number during parsing */
currentLine: number;
/** Generated JavaScript source code */
source: string;
/** Template options */
opts: object;
/** Regular expression for parsing */
regex: RegExp;
}The Template class uses different modes during parsing:
/**
* Template parsing modes enumeration
*/
Template.modes = {
/** Evaluation mode: <% code %> */
EVAL: 'eval',
/** Escaped output mode: <%= expression %> */
ESCAPED: 'escaped',
/** Raw output mode: <%- expression %> */
RAW: 'raw',
/** Comment mode: <%# comment %> */
COMMENT: 'comment',
/** Literal mode: <%% literal %> */
LITERAL: 'literal'
};Usage Examples:
const ejs = require("ejs");
// Access modes
console.log(ejs.Template.modes.EVAL); // 'eval'
console.log(ejs.Template.modes.ESCAPED); // 'escaped'
console.log(ejs.Template.modes.RAW); // 'raw'
// Create template and examine parsing
const template = new ejs.Template(`
<h1><%= title %></h1>
<% if (showDetails) { %>
<p><%- details %></p>
<% } %>
<%# This is a comment %>
`);
// Generate source to see compiled JavaScript
template.generateSource();
console.log(template.source);The Template class allows for fine-grained control over the compilation process:
const ejs = require("ejs");
// Create template with custom options
const template = new ejs.Template(templateText, {
delimiter: '%',
openDelimiter: '<',
closeDelimiter: '>',
strict: true,
_with: false,
localsName: 'locals',
destructuredLocals: ['user', 'config'],
outputFunctionName: 'print'
});
// Examine the parsing regex
console.log(template.regex);
// Parse template into tokens
const tokens = template.parseTemplateText();
console.log(tokens);
// Generate source code
template.generateSource();
console.log(template.source);
// Compile to function
const compiledFn = template.compile();Templates can use custom delimiters for different syntax preferences:
// Use different delimiters: [? ?] instead of <% %>
const template = new ejs.Template("Hello [?= name ?]!", {
delimiter: '?',
openDelimiter: '[',
closeDelimiter: ']'
});
const fn = template.compile();
const html = fn({ name: "World" }); // "Hello World!"The Template class generates JavaScript source code that can be examined:
const template = new ejs.Template(`
<h1><%= title %></h1>
<% users.forEach(user => { %>
<p><%= user.name %></p>
<% }); %>
`);
template.generateSource();
// Examine generated source
console.log(template.source);
// Output will be JavaScript code like:
// var __output = "";
// function __append(s) { if (s !== undefined && s !== null) __output += s }
// with (locals || {}) {
// ; __append("<h1>")
// ; __append(escapeFn( title ))
// ; __append("</h1>\n")
// ; users.forEach(user => {
// ; __append("\n <p>")
// ; __append(escapeFn( user.name ))
// ; __append("</p>\n")
// ; });
// ; __append("\n")
// }
// return __output;Template instances provide detailed error context when compilation fails:
try {
const template = new ejs.Template("<%=invalid syntax%>", {
filename: "test.ejs",
compileDebug: true
});
template.compile();
} catch (error) {
// Error includes filename, line number, and source context
console.log(error.message);
// test.ejs:1
// >> 1| <%=invalid syntax%>
//
// SyntaxError: Unexpected token 'syntax'
}Debug mode provides insight into template compilation:
const template = new ejs.Template(templateText, {
debug: true, // Log generated source code
compileDebug: true // Include debug info in compiled function
});
// This will log the generated JavaScript source
const fn = template.compile();Install with Tessl CLI
npx tessl i tessl/npm-ejs