Core template compilation functionality for converting EJS template strings into reusable JavaScript functions.
Compiles an EJS template string into a template function that can be executed multiple times with different data.
/**
* Compile the given template string into a template function
* @param template - EJS template string
* @param opts - Compilation options
* @returns Template function (server-side) or client function (client-side)
*/
function compile(template, opts);The compiled function signature depends on compilation options:
// Server-side template function (default)
type TemplateFunction = (data?: object) => string;
// Client-side template function (when opts.client = true)
type ClientFunction = (locals, escapeFn, include, rethrow) => string;
// Async template function (when opts.async = true)
type AsyncTemplateFunction = (data?: object) => Promise<string>;Usage Examples:
const ejs = require("ejs");
// Basic compilation
const template = "<h1><%= title %></h1>";
const compiledTemplate = ejs.compile(template);
// Use the compiled template multiple times
const output1 = compiledTemplate({ title: "Hello" });
const output2 = compiledTemplate({ title: "World" });
// Compilation with options
const compiledWithOptions = ejs.compile(template, {
filename: "greeting.ejs",
cache: true,
compileDebug: true
});
// Client-side compilation
const clientTemplate = ejs.compile(template, { client: true });
// Returns a function that can be executed in the browser
// Async compilation
const asyncTemplate = ejs.compile(template, { async: true });
asyncTemplate({ title: "Async" }).then(result => console.log(result));Key options that affect the compilation process:
interface CompilationOptions {
/** Generate client-side template function */
client?: boolean;
/** Template filename for includes and error reporting */
filename?: string;
/** Enable template caching */
cache?: boolean;
/** Enable compilation debug information */
compileDebug?: boolean;
/** Enable debug output during compilation */
debug?: boolean;
/** Generate async template function */
async?: boolean;
/** Strict mode - disables 'with' statement */
strict?: boolean;
/** Custom escape function for output */
escapeFunction?: Function;
/** Custom delimiters */
delimiter?: string;
openDelimiter?: string;
closeDelimiter?: string;
/** Name of locals object in template */
localsName?: string;
/** Name of output function in template */
outputFunctionName?: string;
/** Remove whitespace from template */
rmWhitespace?: boolean;
/** Enable/disable 'with' statement */
_with?: boolean;
/** List of locals to destructure */
destructuredLocals?: string[];
/** Function execution context */
context?: object;
}Compilation can throw several types of errors:
try {
const template = ejs.compile("<%=invalid javascript%>");
} catch (error) {
// SyntaxError: Invalid JavaScript in template
console.log(error.message);
}
try {
const template = ejs.compile("<%=value%>", {
outputFunctionName: "123invalid"
});
} catch (error) {
// Error: outputFunctionName is not a valid JS identifier
console.log(error.message);
}When client: true is specified, EJS generates a self-contained function that can run in browsers:
const ejs = require("ejs");
const template = "<h1><%= title %></h1>";
const clientFn = ejs.compile(template, { client: true });
// The clientFn is a string containing JavaScript code
// that can be executed in the browser
console.log(typeof clientFn); // 'function'
// Can be serialized and sent to client
const clientCode = clientFn.toString();Async templates support promises and async/await patterns:
const asyncTemplate = ejs.compile(`
<h1><%= title %></h1>
<% for (const item of await items) { %>
<p><%= item.name %></p>
<% } %>
`, { async: true });
// Use with async data
const result = await asyncTemplate({
title: "Async Example",
items: Promise.resolve([
{ name: "Item 1" },
{ name: "Item 2" }
])
});