Lodash _.template() Method
Lodash _.template() method is used to create a template function that is compiled and can interpolate properties of data in interpolate delimiters, execute JavaScript in evaluate delimiters, and HTML-escape interpolated properties of data in escape delimiters. Moreover, data properties are retrieved in the template as free variables.
Syntax:
_.template([string=''], [options={}])
;
Parameters:
- string: It is a string that would be used as the template. It is an optional value.
- options: It is an object that can be used to modify the behavior of the method. It is an optional value.
- options.interpolate: It is a regular expression that specifies the HTML interpolate delimiter.
- options.evaluate: It is a regular expression that specifies the HTML evaluate delimiter.
- options.escape: It is a regular expression that specifies the HTML escape delimiter.
- options.imports: It is an object which is to be imported as free variables into the template.
- options.sourceURL: It is a string that denotes the source URL of the compiled template.
- options.variable: It is a string that denotes the variable name of the data object.
Return Value:
This method returns the compiled template function.
Example 1: In this example, we are passing a string into the _.template() method.
Javascript
const _ = require( 'lodash' );
let comptempl =
_.template( 'Hi <%= author%>!' );
let result =
comptempl({ 'author' : 'Nidhi' });
console.log(result);
|
Output:
Hi Nidhi!
Example 2: In this example, we are passing a string into the _.template() method. and printing the ‘geek’ into the console.
Javascript
const _ = require( 'lodash' );
let comptempl = _.template(
'<% print("hey " + geek); %>...'
);
let result =
comptempl({ 'geek' : 'Nisha' });
console.log(result);
|
Output:
hey Nisha...
Example 3: In this example, we are passing a string into the _.template() method. The forEach() method is used as the evaluate delimiter in order to generate HTML as output.
Javascript
const _ = require( "lodash" );
let compiled_temp = _.template(
"<% _.forEach(students, function(students) " +
"{ %><li><b><%- students %></b></li><% }); %>"
)({ students: [ "Rahul" , "Rohit" ] });
console.log(compiled_temp);
|
Output:
<li><b>Rahul</b></li><li><b>Rohit</b></li>
Last Updated :
20 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...