Underscore.js is a JavaScript library that provides a lot of useful functions that help in the programming in a big way like the map, filter, invokes, etc even without using any built-in objects.
The _.template() function is an inbuilt function in the Underscore.js library of JavaScript which is used to compile JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources.
Template functions to create a template function that is compiled and can interpolate properties of data in interpolating delimiters, execute JavaScript in evaluating delimiters, and HTML-escape interpolated properties of data in escape delimiters. Moreover, data properties are retrieved in the template as free variables.
Syntax:
_.template(templateString, [settings])
Parameters: This method accepts two parameters as mentioned above and described below:
- templateString: It is a string that would be used as the template.
- settings: It is an object that must be a hash containing any _.templateSettings that should be overridden.
Return Value: This method returns the compiled template function.
Example 1:
HTML
<!DOCTYPE html> < html > < head > < script src = </ script > </ head > < body > < script > // Using the template() method with // additional parameters let compiled_temp = _.template( "<% _.forEach(students, function(students) " + "{ %>< li >< b ><%- students %></ b ></ li ><% }); %>" )({ students: ["Shubham", "Shakya"] }); // Displays the output console.log(compiled_temp); </ script > </ body > </ html > |
Output:
Hi Shubham!
Example 2:
HTML
<!DOCTYPE html> < html > < head > < script src = </ script > </ head > < body > < script > // Using the _.template() method to // create a compiled template using // the internal print function in // the "evaluate" delimiter var comptempl = _.template("<% print('hey ' + geek); %>..."); // Assigning value to the evaluate delimiter let result = comptempl({ 'geek': 'Shubham' }); // Displays output console.log(result); </ script > </ body > </ html > |
Output:
hey Shubham...
Example 3:
HTML
<!DOCTYPE html> < html > < head > < script src = </ script > </ head > < body > < script > // Using the template() method with // additional parameters let compiled_temp = _.template( "<% _.forEach(students, function(students) " + "{ %>< li >< b ><%- students %></ b ></ li ><% }); %>" )({ students: ["Shubham", "Shakya"] }); // Displays the output console.log(compiled_temp); </ script > </ body > </ html > |
Output:
<li><b>Shubham</b></li><li><b>Shakya</b></li>
Reference: https://underscorejs.org/#template