{

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.

This tutorial covers the template function with basic examples.
You can also check other posts on lodash library.

Lodash Templates syntax

Templates are used to format, bind, and display javascript data. It enables to binding of the javascript data to the HTML template.

templates are the strings of HTML code and markup, that complies with javascript data, and output new DOM element.

There are two parts, One is writing a template, second is calling this using the template function.

_.template(templateString)  

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 plain strings 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 is inserted in different ways.

Interpolate delimiter

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

Syntax

<%=variables/expression%>  

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

escape delimiter expression

It 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 to 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.