How to use underscore.js as a template engine?


A straightforward and lightweight templating technique for creating dynamic information within HTML is offered by the JavaScript library known as Underscore.js. A template must be defined in the HTML file using the script tag and a custom type attribute to use underscore.js as a template engine. The template should be contained in the script tag's contents, which can also contain variables and JavaScript expressions.

The _.template() function compiles the template and returns a function that can be called with data object to produce the desired result. The ability to call the built function with any data object makes creating dynamic content on the fly simple.

After the template has been put together, JavaScript libraries like jQuery can be used to integrate the resulting HTML into the DOM. This enables a user to develop interactive, dynamic web pages that update in real-time in response to user input.

As a template engine, underscore.js offers a quick and adaptable approach to creating dynamic content for HTML. It is beneficial when building intricate UI elements like lists and tables where the data needs to be dynamically rendered and updated often. Making templates using underscore.js that react to data changes and alter the UI in real-time is simple, making it a potent tool for developing dynamic web applications.

Steps to use Underscore.js

These instructions will show the user how to use Underscore.js as a template engine to create dynamic content for HTML. Creating sophisticated UI components with little code is simple because the produced templates can be reused numerous times with various data types. Moreover, the template's usage of JavaScript expressions enables the inclusion of complicated logic, enabling the creation of highly personalized and dynamic UI elements.

  • Make sure the HTML file uses the Underscore.js library. Downloading the library from the Underscore.js website or including it through a CDN are viable options.

  • Use the script tag and a custom-type property to define the template in the HTML file. The template should be contained in the script tag's contents, which can also contain variables and JavaScript expressions.

  • Use the _.template() method to compile the template, which converts the script tag's contents into a function. To produce the desired result, the compiled function can be called along with a data object.

  • Call the built template function with a data object to produce the final HTML result. Any JavaScript object containing the data displayed in the template can serve as the data object.

  • Use JavaScript to insert the created HTML into the DOM. jQuery or any other JavaScript library with DOM manipulation functions can be used for this.

Example 1

In this example, we use underscore.js as a template engine and show multiple data values on the template. We first add the CDNs of jQuery and Underscore.js. Then we define an object containing all the information we want to show on the web page. Then we created a template and used the info object’s value with the desired syntax. We also showed how to use a list and loop through a list to get all the values.

<html>
<head>
   <script src = "https://code.jquery.com/jquery-3.6.3.min.js"></script>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"> </script>
</head>
<body>
   <script type = "text/template" id = "root-template">
      <h2> <%= title %> </h2>
      <h4> Name: <%= name %> </h4>
      <h4> Books: </h4>
      <ul>
         <% _.each(books, function(book) { %>
            <li><%= book %></li>
         <% }); %>
      </ul>
   </script>
   <div id = "root" > </div>
   <script>
      var info = {
         title: 'Using underscore.js as a template engine',
         name: 'ABC XYZ',
         books: ['Book 1', 'Book 2', 'Book 3'],
      }
      var compiledTemplate = _.template($('#root-template').html())
      var html = compiledTemplate(info)
      $('#root').html(html)
   </script>
</body>
</html>

Example 2

In this example, we will use underscore.js as a template engine to loop through an array of objects and show the values on the webpage in a tabular format. Firstly we add the CDNs of jQuery and Underscore.js. Then we define the object array containing all the information we want to show on the web page. Then we will create the template and loop through the array.

<html>
<head>
   <script src = "https://code.jquery.com/jquery-3.6.3.min.js"></script>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"> </script>
   <style>
      table, th, td {
         border: 1px solid black;
         border-collapse: collapse;
      }
   </style>
</head>
<body>
   <script type = "text/template" id = "root-template">
      <h2> <%= title %> </h2>
      <p> The Student data is as follows: </p>
      <table >
         <thead>
            <tr>
               <th> Name </th>
               <th> Roll number </th>
               <th> Marks </th>
            </tr>
         </thead>
         <tbody>
            <% _.each(students, function(student) { %>
               <tr>
                  <td> <%= student.name %> </td>
                  <td> <%= student.roll %> </td>
                  <td> <%= student.marks %> </td>
               </tr>
            <% }); %>
         </tbody>
      </table>
   </script>
   <div id = "root"> </div>
   <script>
      var info = {
         title: 'Using underscore.js as a template engine',
         students: [
            { name: 'ABC', roll: 1, marks: 90 },
            { name: 'XYZ', roll: 2, marks: 80 },
            { name: 'MNO', roll: 3, marks: 92 },
            { name: 'IJK', roll: 4, marks: 5 },
         ],
      }
      var compiledTemplate = _.template($('#root-template').html())
      var html = compiledTemplate(info)
      $('#root').html(html)
   </script>
</body>
</html>

Underscore.js is a very easy-to-use template engine that can be used to develop a web application quickly.

Updated on: 06-Apr-2023

555 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements