O'Reilly logo

jQuery Cookbook by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

17.4. Using a JavaScript Template Engine

Problem

You want to use a JavaScript template engine to display JSON data.

Solution

This recipe is a book listing. It grabs information about a book from a server-side script and adds it to a list of books displayed in the browser. The book details are returned from the server as a JSON string. The Pure templating engine (available at http://plugins.jquery.com/project/pure) is used to format the data and insert it into the web page:

<!DOCTYPE html>
<html><head>
    <title>jQuery Cookbook - 17.4 Using a Javascript Template Engine</title>
    <style>.hidden { display: none }</style>
    <script type="text/javascript" src="../../jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="pure.js"></script>
</head>

<body>
    <h1>17.4 - Using a Javascript Template Engine</h1>
    <input type="button" id="add-book" value="Add book"></input>
    <input type="button" id="clear-list" value="Clear booklist"></input>
    <div id="book-list"></div>

There are two buttons. One will fetch book details from the server when clicked. The other will clear the locally displayed book list. The book list will be displayed inside a <div> element with an id of book-list. These elements are visible when the page is loaded:

 <div id="book-template" class="hidden book"> <ul class="author-list"><li class="author"><span class="name"></span> </li></ul> <p class="title"></p> <p class="year"></p> <div class='book-footer'> <div class="rating-div">Rating: <span class="rating"></span></div> <div>Location: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required