Lodash template function in javascript tutorials with examples

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

What is Lodash Templates

Templates🔗 function used to write a functions, compile, bind and replace javascript object data at runtime.. It enables to binding of the javascript data to the HTML template.

Lodash Templates syntax:

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, options);

templateString are the strings of HTML code and markup options for a template function. options are

  • escape
  • Evalaute
  • imports
  • interpolate
  • sourceURL
  • variable

How to declare String Template in Lodash

  • Create a HTML content as a string as a script tag Inside 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.

Template data 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:'john'};
   var template=_.template(nameDisplayTempateStr);
   var rendered=template(nameData);
  ` $('#output').html(rendered);
</script>

the output is hello john displayed on the browser