JSRender

What is JsRender?
Many development platforms use templates to reduce code and simplify maintenance, and HTML5 and JavaScript are no exception. JsRender is a JavaScript library that allows you to define a boilerplate structure once and reuse it to generate HTML dynamically. JsRender brings a new templating library to HTML5 development that has a codeless tag syntax and high performance, has no dependency on jQuery nor on the Document Object Model (DOM), supports creating custom functions and uses pure string-based rendering.

Why Templates?
Using templates with JavaScript reduces and simplifies code. Without templates, adding a series of list items and other HTML elements for a set of data might require manipulating a browser’s DOM. This is where templating using a plug-in such as JsRender can be quite useful to do the heavy lifting.

Practice

demo.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<!DOCTYPE html>
<html>
<head>
  <script src="js/jquery.min.js" type="text/javascript"></script>
  <script src="js/jsrender.js" type="text/javascript"></script>
  <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />

  <script id="book_template" type="text/x-jsrender">
    <tr>
      <td>{ {:#index+1} } </td>
      <td>{ {>name} }</td>
      <td>{ {>releaseYear} }</td>
    </tr>
  </script>

  <script type="text/javascript">
    $(document).ready(function() {
      var books = [
        { name: "Erlang", releaseYear: "1986" },
        { name: "Ruby", releaseYear: "1998" },
        { name: "Ruby on Rails", releaseYear: "1999" },
        { name: "Javascript", releaseYear: "1976" }
      ];

      $("#book_list").html(
        $("#book_template").render(books)
      );
    });
  </script>

</head>
<body>
  <div class="container">
    <section id="fluidGridSystem">
      <div class="page-header">
        <h3>Render template against local data</h3>
      </div>
      <div class="row-fluid show-grid">
        <table class="table table-bordered">
          <thead>
            <tr>
              <th>No</th>
              <th>Name</th>
              <th>Release Year</th>
            </tr>
          </thead>
          <tbody id="book_list">
          </tbody>
        </table>
      </div>
    </section>
  </div>
</body>
</html>

You can download the source code and try it out.