0
# Lodash Template
1
2
Lodash Template is a JavaScript templating engine that compiles template strings into functions for rendering dynamic content. It supports multiple template delimiters for interpolation, HTML escaping, and code evaluation, along with ES6 template literal syntax, making it versatile for web applications, static site generators, and any dynamic string generation needs.
3
4
## Package Information
5
6
- **Package Name**: lodash.template
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install lodash.template`
10
11
## Core Imports
12
13
```javascript
14
const template = require('lodash.template');
15
```
16
17
For ES6/TypeScript:
18
19
```javascript
20
import template from 'lodash.template';
21
```
22
23
## Basic Usage
24
25
```javascript
26
const template = require('lodash.template');
27
28
// Basic interpolation
29
const compiled = template('Hello <%= name %>!');
30
const result = compiled({ name: 'World' });
31
// => 'Hello World!'
32
33
// HTML escaping
34
const safeTemplate = template('<div><%- userInput %></div>');
35
const safeResult = safeTemplate({ userInput: '<script>alert("xss")</script>' });
36
// => '<div><script>alert("xss")</script></div>'
37
```
38
39
## Capabilities
40
41
### Template Compilation
42
43
Creates a compiled template function from a template string with various delimiter options and configuration settings.
44
45
```javascript { .api }
46
/**
47
* Creates a compiled template function that can interpolate data properties
48
* @param {string} [string=''] - The template string
49
* @param {Object} [options] - The options object
50
* @param {RegExp} [options.escape] - The HTML "escape" delimiter
51
* @param {RegExp} [options.evaluate] - The "evaluate" delimiter
52
* @param {Object} [options.imports] - An object to import into the template as free variables
53
* @param {RegExp} [options.interpolate] - The "interpolate" delimiter
54
* @param {string} [options.sourceURL] - The sourceURL of the template's compiled source
55
* @param {string} [options.variable] - The data object variable name
56
* @param {Object} [otherOptions] - Enables the legacy options param signature
57
* @returns {Function} Returns the compiled template function
58
*/
59
function template(string, options, otherOptions);
60
```
61
62
**Template Delimiters:**
63
64
- **Interpolation**: `<%= ... %>` - Outputs values directly
65
- **Escaping**: `<%- ... %>` - HTML-escapes and outputs values
66
- **Evaluation**: `<% ... %>` - Executes JavaScript code
67
- **ES6 Template**: `${ ... }` - Alternative interpolation syntax
68
69
**Usage Examples:**
70
71
```javascript
72
const template = require('lodash.template');
73
74
// Interpolation delimiter
75
const interpolated = template('Hello <%= user %>!');
76
console.log(interpolated({ user: 'Alice' }));
77
// => 'Hello Alice!'
78
79
// HTML escape delimiter
80
const escaped = template('<b><%- value %></b>');
81
console.log(escaped({ value: '<script>' }));
82
// => '<b><script></b>'
83
84
// Evaluate delimiter with loops
85
const evaluated = template('<% users.forEach(function(user) { %><li><%- user %></li><% }); %>');
86
console.log(evaluated({ users: ['Alice', 'Bob'] }));
87
// => '<li>Alice</li><li>Bob</li>'
88
89
// Using print function in evaluate blocks
90
const withPrint = template('<% print("Hello " + name); %>!');
91
console.log(withPrint({ name: 'World' }));
92
// => 'Hello World!'
93
94
// ES6 template literal syntax
95
const es6Template = template('Hello ${ user }!');
96
console.log(es6Template({ user: 'Charlie' }));
97
// => 'Hello Charlie!'
98
99
// Escaping delimiters with backslashes
100
const escapedTemplate = template('<%= "\\<%- value %\\>" %>');
101
console.log(escapedTemplate({ value: 'ignored' }));
102
// => '<%- value %>'
103
```
104
105
### Template Options Configuration
106
107
Customize template compilation with delimiter configuration, variable scoping, and import functionality.
108
109
```javascript { .api }
110
interface TemplateOptions {
111
/** RegExp pattern for HTML escape delimiters (default: lodash.templateSettings.escape) */
112
escape?: RegExp;
113
/** RegExp pattern for evaluate delimiters (default: lodash.templateSettings.evaluate) */
114
evaluate?: RegExp;
115
/** Object containing variables to import into template scope */
116
imports?: Object;
117
/** RegExp pattern for interpolate delimiters (default: lodash.templateSettings.interpolate) */
118
interpolate?: RegExp;
119
/** Source URL for debugging compiled templates */
120
sourceURL?: string;
121
/** Variable name for data object to avoid with-statement usage */
122
variable?: string;
123
}
124
```
125
126
**Usage Examples:**
127
128
```javascript
129
const template = require('lodash.template');
130
131
// Custom delimiters
132
const customTemplate = template('Hello {{ name }}!', {
133
interpolate: /\{\{([\s\S]+?)\}\}/g
134
});
135
console.log(customTemplate({ name: 'Mustache' }));
136
// => 'Hello Mustache!'
137
138
// Importing external libraries
139
const compiled = template('<% _.each(users, function(user) { %><li><%- user %></li><% }); %>', {
140
imports: { '_': require('lodash') }
141
});
142
console.log(compiled({ users: ['Alice', 'Bob'] }));
143
// => '<li>Alice</li><li>Bob</li>'
144
145
// Using variable option to avoid with-statement
146
const withVariable = template('Hello <%= data.name %>!', {
147
variable: 'data'
148
});
149
console.log(withVariable({ name: 'TypeScript' }));
150
// => 'Hello TypeScript!'
151
152
// Source URL for debugging
153
const debugTemplate = template('Hello <%= name %>!', {
154
sourceURL: '/templates/greeting.jst'
155
});
156
// Template function will have source mapping for debugging
157
```
158
159
### Compiled Template Function
160
161
The function returned by template compilation with properties and usage patterns.
162
163
```javascript { .api }
164
interface CompiledTemplate {
165
/**
166
* Execute the compiled template with data
167
* @param {Object} data - Data object to render template with
168
* @returns {string} Rendered template string
169
*/
170
(data?: Object): string;
171
172
/** Source code of the compiled template function for inspection */
173
source: string;
174
}
175
```
176
177
**Usage Examples:**
178
179
```javascript
180
const template = require('lodash.template');
181
182
// Create and use compiled template
183
const compiled = template('Name: <%= name %>, Age: <%= age %>');
184
const result = compiled({ name: 'Alice', age: 30 });
185
// => 'Name: Alice, Age: 30'
186
187
// Access source code for inspection
188
console.log(compiled.source);
189
// => 'function(obj) {\n obj || (obj = {});\n var __t, __p = \'\';\n...'
190
191
// Using the source property for inline template generation
192
const fs = require('fs');
193
const path = require('path');
194
const mainTemplate = template('Hello <%= user %>!');
195
const jsCode = `
196
var JST = {
197
"greeting": ${mainTemplate.source}
198
};
199
`;
200
// Write compiled template as JavaScript module
201
202
// Reuse compiled template with different data
203
const user1 = compiled({ name: 'Bob', age: 25 });
204
const user2 = compiled({ name: 'Carol', age: 35 });
205
```
206
207
### Error Handling
208
209
Template compilation and execution error handling patterns.
210
211
The template function internally handles compilation errors and will throw if compilation fails. For error handling in template execution, use standard JavaScript try/catch blocks.
212
213
**Usage Examples:**
214
215
```javascript
216
const template = require('lodash.template');
217
218
// Handle compilation errors
219
try {
220
const compiled = template('Invalid template: <%= %>');
221
} catch (error) {
222
console.log('Template compilation failed:', error.message);
223
}
224
225
// Handle template execution errors
226
const compiled = template('<%= data.deeply.nested.value %>');
227
try {
228
const result = compiled({ data: {} });
229
} catch (error) {
230
console.log('Template execution failed:', error.message);
231
}
232
233
// Safe template execution with fallback
234
function safeTemplate(templateStr, data, fallback = '') {
235
try {
236
const compiled = template(templateStr);
237
return compiled(data);
238
} catch (error) {
239
console.error('Template error:', error.message);
240
return fallback;
241
}
242
}
243
```
244
245
## Template Settings Integration
246
247
Lodash.template integrates with global template settings for default delimiter configuration.
248
249
```javascript { .api }
250
/**
251
* Global template settings object (via lodash.templatesettings dependency)
252
*/
253
interface TemplateSettings {
254
/** Default RegExp for escape delimiters */
255
escape: RegExp;
256
/** Default RegExp for evaluate delimiters */
257
evaluate: RegExp;
258
/** Default RegExp for interpolate delimiters */
259
interpolate: RegExp;
260
/** Default imports object for template scope */
261
imports: {
262
_: Object; // lodash utilities
263
};
264
}
265
```
266
267
**Usage Examples:**
268
269
```javascript
270
const template = require('lodash.template');
271
const templateSettings = require('lodash.templatesettings');
272
273
// Modify global template settings
274
templateSettings.interpolate = /\{\{([\s\S]+?)\}\}/g;
275
276
// Templates created after this will use new delimiters by default
277
const compiled = template('Hello {{ name }}!');
278
console.log(compiled({ name: 'Global' }));
279
// => 'Hello Global!'
280
281
// Individual templates can still override global settings
282
const customCompiled = template('Hello <%= name %>!', {
283
interpolate: /<%=([\s\S]+?)%>/g
284
});
285
```
286
287
## Advanced Features
288
289
### Template Compilation Process
290
291
Understanding the internal compilation process for advanced usage patterns.
292
293
1. **Input Processing**: Template strings are normalized and options are merged with global settings
294
2. **Delimiter Compilation**: Regular expressions are created to match template delimiters
295
3. **Source Generation**: Template string is parsed and JavaScript function source is generated
296
4. **Function Creation**: Function constructor creates executable template with proper scope
297
5. **Error Handling**: Compilation errors are caught and wrapped in Error objects
298
299
### Security Considerations
300
301
- **HTML Escaping**: Use `<%-` delimiters to prevent XSS attacks when outputting user data
302
- **Code Injection**: Evaluate delimiters `<%` execute arbitrary JavaScript - validate template sources
303
- **Variable Scoping**: Use `variable` option to avoid `with` statements and improve security
304
- **Import Safety**: Be cautious when providing external libraries via `imports` option
305
306
### Performance Optimization
307
308
- **Pre-compilation**: Compile templates once and reuse with different data
309
- **Source Caching**: Store compiled template functions to avoid repeated compilation
310
- **Variable Scoping**: Use `variable` option for better performance and security
311
- **Import Management**: Minimize imports object size for faster template execution
312
313
### Browser Compatibility
314
315
- Designed primarily for Node.js environments
316
- Requires CommonJS module system
317
- No browser-specific APIs used in core functionality
318
- Can be bundled for browser use with appropriate module bundlers