Monday, August 6, 2018

Lodash template function tutorials with examples

Understanding Lodash Templates 

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

syntax

_.template(templateString)
Templates are used to format, bind and displays 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 write a template and calling this using template function

String Template Declaration 

Inside HTML content as a string using script tag. Dynamic data replaced 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 can be accessed like the normal way. variables are manipulated at runtime.
Browsers assume that script tag as javascript code, To prevent execute this in the browser, Use type as text/template. Id 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 as these.

Syntax

<%=variables/expression%>
Here the result of variable or expression is evaluated at runtime and returned data as 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

Evaluates the code.code can contain loops and conditional expression. 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

Related article


EmoticonEmoticon