/handlebars

[handlebars, templating]

Primary LanguageJavaScript

Handlebars Templating

Why is this important?

This workshop is important because:

  • Front End Templating allows for dynamic HTML views without messily concatenating HTML strings.
  • Helps separate the business logic from the presentation logic
  • Handlebars is one of the most popular front end templating engines

What are the objectives?

After this workshop, developers will be able to:

  • Add the Handlebars.js library to your projects
  • Create and compile a Handlebars template
  • Use Handlebars templating to display data from an AJAX call on your HTML page

Where should we be now?

Before this workshop, developers should already be able to:

  • Create dynamic web pages with HTML, JS, and CSS
  • Use a CDN to pull in an external library

What is a template?

  • A template is a document (or piece of code) that contains blank spaces for data.

  • A template function is a function that takes in such a document and data and returns a dynamic HTML string.

  • Thus far, we've been using jQuery to append HTML strings to the DOM when we have data to display in the browser.

  • To avoid building long strings of HTML every time we have data to send to the view, we'll use Handlebars templating. This will allow us to dynamically display data in our HTML. The parameters for our data will live inside {{}} tags.

Why use client-side templating?

  • Separate markup from logic. Remember this?

    $('#student-list').append('<li class="student">' + firstName + ' - ' + lastName + '</li>');
    • When appending new HTML elements to the page, the string of elements to append will only get longer as you begin to write more complex markup.

    • Wouldn't it be nice if the HTML structure was already set up for us? That's where templating comes in!

  • Maximize code reusability and maintainability.

    • If you need to change your HTML structure for elements you're creating and displaying (e.g. adding an additional class name to your Books), all you have to do is change the template!

A Helpful Metaphor

Think of a template as a mold, the data passed in as plastic poured in, and the resulting html string that is generated as a cast.

novelty cake tin - bug shaped cakes



A template is like a mold

Explore Handlebars

We'll use the HTML strings lab as our starting point. Check out the solution branch.

What is happening in index.html?

Create a mold

  1. We make a script tag with an id that describes what the template will be. The script tag should also have type="text/x-handlebars-template"; this is important for Handlebars!

  2. Using Handlebars, we create a structure we'd like to use for part of the page. Ours is for each student's link. This structure should be inside the script tag. Note the use of {{ }} to identify where data will go.

  3. We make sure that the data format we use matches the format of the javascript Object { } that contains the data that we'll use. The example above uses student data. In this example, each student has a first_name, a last_name, and a github_username.

Set up a factory line

  1. Using #each in the template lets Handlebars know we'll want to repeat the structure inside the #each for every element of the array.

What is happening in app.js?

Select something to mold

  1. Using jQuery we select our students-list-template script element.

Make the mold

  1. We give the element's inner html to Handlebars' compile function. Handlebars generates a template function for us (our html mold, if you wish).

Pour the plastic into the mold

  1. The template from our html expects an array of students. We send the template data27.students to use as students first. Then we use the template function again with data28.students as students.

Open our mold to find a casting!

  1. Each time we call it, the template function returns a string of html that it has generated by mashing the data into the template.

Put the casting on display

  1. We use jQuery to select the element where we want the new HTML to appear, then append the generated html strings to the page using jQuery.

General Handlebars Setup Steps

with http://daretoexplore.herokuapp.com/books examples

  1. Add the Handlebars CDN to your index.html (remember you can go to cdnjs to search for CDNs). Make sure to require Handlebars before your custom script file.
<head>
  <!-- meta tags, title, css links -->
  <!-- ... -->

  <!-- jquery -->
  <script type="text/javascript" src="http://code.jquery.com/jquery-2.2.2.min.js" integrity="sha256-36cp2Co+/62rEAAYHLmRCPIych47CvdM+uTBJwSzWjI=" crossorigin="anonymous"></script>

  <!-- handlebars -->
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>

  <!-- custom script -->
  <script type="text/javascript" src="js/app.js"></script>
</head>
  1. Next create an element in your index.html where you will append the data from your template. Give this element an id (e.g. results) so you can select it very specifically with jQuery.
<body>
  <div class="container">
    <div class="row">
      <div class="col-md-6 col-md-offset-3">
        <div id="results">
        </div>
      </div>
    </div>
  </div>
</body>
  1. Create an element where you'll append the elements generated by Handlebars, and give it an id so you can select it later. Then create a script element; this is your template! Give your template script an id (e.g. students-list-template) so you can select it with jQuery. This template acts as an HTML "mad lib", "mold", or "cake pan" which you'll fill with data. The {{}} parameters will be replaced by the data that comes back from your API call.

    <body>
      <div class="container">
        <div class="row">
          <div class="col-md-6 col-md-offset-3">
            <div id="results">
    
              <!-- handlebars template -->
              <script id="books-template" type="text/x-handlebars-template">
                {{#each book}}
                  <p><strong>{{title}}</strong> | by {{author}}</p>
                {{/each}}
              </script>
    
            </div>
          </div>
        </div>
      </div>
    </body>
  2. Compile your template in app.js. Handlebars has a function called Handlebars.compile(source). The source it takes in is the html from inside your template script. Handlebars' compile function returns a function, which we'll save to a variable called template. This isn't a special variable name; it just reminds us what the function does.

// compile handlebars template
var source = $('#books-template').html();
var template = Handlebars.compile(source);
  1. Pass the data you want to display into your template function. If you're getting data from an AJAX call, you'll want to do this once the call has been successful. The output of the template function is an HTML string that contains your data. Make sure you give the template function an object with data to fill in each blank from your html template.
// this is the success handler for an AJAX call
function renderBookData(data) {
  console.log(data);

  // ...

  // pass in data to render in the template
  var trackHtml = template({ book: data });
}
  1. The last step is to append the new HTML string to the view.
function renderBookData(data) {
  // track results are in an array called `items`
  // which is nested in the `books` object
  var bookResults = data.books.items;
  console.log(bookResults);

  // ...

  // pass in data to render in the template
  var trackHtml = template({ book: bookResults });

  // append html to the view
  $results.append(trackHtml);
}

Independent Practice

You will refine the skills covered in this workshop in the labs this afternoon.

Closing Thoughts

  • Templating is used to mold data into the HTML we want it to be displayed in
  • It can be done on the front end or back end, as we will learn later in the program.
  • You should know what templating is for and how to implement it in a strait forward use case.
  • You should start to get the idea of what the use cases are for templating.

Additional Resources