{

Lodash template function tutorials with examples


Understanding Lodash Templates

Lodash is a popular javascript library that provides simple utility reusable functions. It also provides string template manipulation. In this tutorial, we will cover the template function basics with examples.
It is continuing post of following previous articles on lodash library.

syntax

_.template(templateString)  

Templates are used to format, bind, and display javascript data. It enables to bind the javascript data to HTML template. templates are the strings of HTML code and markup, complies with javascript data, output new DOM element. There are two parts to writing a template and calling this using the template function.

String Template Declaration

Inside HTML content as a string using a script tag. Dynamic data do replace with javascript object data. Here data can be retrieved using a variable. variables are a plain string or any object used in a delimited format like below. Object properties do access like the normal way. variables manipulate at runtime.
Browsers assume that script tag as javascript code, To prevent executing this in the browser, Use type as text/template. It has required an attribute to retrieve the template in javascript code.

<script type="text/template" id="DemoTemplate">  
  <p>"Hello {{ name }}!"</p>  
</script>  

Data can be inserted in different ways.

Interpolate delimiter

Here the result of variable or expression is evaluated at runtime and returned data like these.

Syntax

<%=variables/expression%>  

Here the result of variable or expression is evaluated at runtime and returned data like these.

escape delimiter expression

inserts the variable value or result of the expression. Below characters are escaped using _.escape() Function Syntax

<%-variable/expression%>  

Example

_.template("Hello <%-name%>!", { name: "" })  
    'Hello <Jane>!'  

Evaluate delimiter

Evaluate the code.code can contain loops and conditional expressions. We can use forEach and if-else conditions

Syntax

<%code%>  

example

let template = _.template('<% if (marks >35 ) { %> passed! <% } else { %> Failed! <% } %>');  
template({  
  marks: 50  
});  

Calling template string using function code

Using jquery selector retrieve template with id, and pass this template HTML as a string to lodash template function.

<script>  
 var nameDisplayTempateStr = $('#nameDisplayTempate').html();  
    var nameData = {name:'kiran'};  
 var template=_.template(nameDisplayTempateStr);  
 var rendered=template(nameData);  
` $('#output').html(rendered);  
 </script>  

the output is hello Kiran displayed on the browser

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.