Week 10 | April 11, 2016

Templating

Lesson Prep

  • Open: Class Website, Week 10
  • Open your website in sublime
  • Open the template-practice repository from my GitHub page.

Git Lab: branch and pull

Create a pull request for your final method presentation file to be submitted to the final repo.

Templating - WHY?

When building applications or pages the problem will quickly arise where you will need to format part of your page's HTML in your JavaScript files

Templating libraries allow you to quickly create your own templates in your code and on-the-fly to render bulks of data quickly.

Rule of Thumb

If you find yourself writing a few lines of JavaScript soley to form HTML blocks for your page, you might want to utilize a templating library.

Options

A search will yield a handful -but a good place to start is either Underscore or Handlebars (Mustache).

For Example

Say we are researching police incidents caught on tape by body cams and are pulling together a dataset based on the information we find. It might look something like this (Note: This data is made up and should not be published! For example only)

Convert to JSON

You could write out in JSON initially but sometimes a program like Excel is better for pulling information together. Once you're finished, you can convert to JSON using an online program like Mr. Data Converter.

* Result *

Underscore

We are going to go over Underscore, partly because it is a good library to know in general and because it has many useful methods for parsing data.

To use, download the library or find a hosted version to include on your page. For our purposes today we are using a version hosted by cdnjs.

Syntax

  • Run a method: _.methodName(params);
  • Define template: <%= object %>
  • Write JavaScript in a template: <% Your Code Here %>

Underscore has many very useful methods. We will use a few in our example, but make sure to look at the documentation for the full breadth of the library.

Exercise

Using the files from template-practice as a base, let's write a small application that will run through your body cam data and display it on the page.

Method Presentations Part 2

  • As each student presents their method to the class. You can follow along as necessary for your own practice.
  • Once you've presented, make sure your final presentation page is prepared to add to the method-presentations repo.
  • Follow the git pull lab to complete a request to add your method assignment to the repo.

Assignments

Reading

Practice

Do Codecademy's Game exercise to build a "Rock, Paper, Scissors" application to continue practicing writing JavaScript.