template(): ((data?: object) => string) & { source: string; }
Compiles a template string into a function that can interpolate data properties.
This function allows you to create a template with custom delimiters for escaping, evaluating, and interpolating values. It can also handle custom variable names and imported functions.
Example 1
Example 1
// Use the "escape" delimiter to escape data properties. const compiled = template('<%- value %>'); compiled({ value: '
Example 2
Example 2
// Use the "interpolate" delimiter to interpolate data properties. const compiled = template('<%= value %>'); compiled({ value: 'Hello, World!' }); // returns 'Hello, World!'
Example 3
Example 3
// Use the "evaluate" delimiter to evaluate JavaScript code. const compiled = template('<% if (value) { %>Yes<% } else { %>No<% } %>'); compiled({ value: true }); // returns 'Yes'
Example 4
Example 4
// Use the "variable" option to specify the data object variable name. const compiled = template('<%= data.value %>', { variable: 'data' }); compiled({ value: 'Hello, World!' }); // returns 'Hello, World!'
Example 5
Example 5
// Use the "imports" option to import functions. const compiled = template('<%= _.toUpper(value) %>', { imports: { _: { toUpper } } }); compiled({ value: 'hello, world!' }); // returns 'HELLO, WORLD!'
Example 6
Example 6
// Use the custom "escape" delimiter. const compiled = template('<@ value @>', { escape: /<@([\s\S]+?)@>/g }); compiled({ value: '
Example 7
Example 7
// Use the custom "evaluate" delimiter. const compiled = template('<# if (value) { #>Yes<# } else { #>No<# } #>', { evaluate: /<#([\s\S]+?)#>/g }); compiled({ value: true }); // returns 'Yes'
string: string
- The template string.