Harvard Extension School
CSCI E-12 Fundamentals of Web Site Development | Fall 2019

## JavaScript Templates - Courses

Let's take a look at a Handlebars template that processes information about Courses from the Faculty of Arts & Sciences at Harvard University.

Courses - Example Courses - JSFiddle

Course data. First, here is a JSON string built based on a query of the course database for all the courses with a keyword of "food". It would be typical to have this query built from a form and return "live" results in JSON, but to keep things simpler for this example, we'll just use this static list: courses.json

Handlebars template. In this JSON structure, there is an array of course objects (the "name" part is `courses`, the value is the array of course objects). In Mustache, we'll need to iterate through the courses, and for each one, we'll output some information about the course. Assuming we pass the Mustache template the JSON object above, this would look something like:

    <div id="courselisttemplate" class="handlebars">
    <ul>
    {{#courses}}
        <li class="course">
        <span class="number">{{course_group}} {{num_int}}{{num_char}}</span>
        <br/>
        <span class="title">{{title}}</span>
        </li>
    {{/courses}}
    </ul>
    </div>

Notice how we can simply reference the "name" of a name/value pair in an object, like `{{title}}`.

The above template would render like:

We'll make this example a bit more complete by adding the `faculty_text` and `meeting_text` to the output. Also, we can add the number of courses returned by using `{{courses.length}}`.

    <div id="courselisttemplate" class="handlebars">
    <p>{{courses.length}} courses were found</p>
    <ul>
    {{#courses}}
        <li class="course">
        <span class="number">{{course_group}} {{num_int}}{{num_char}}</span>
        <br/>
        <span class="title">{{title}}</span>
        <br/>
        <span class="faculty">{{faculty_text}}</span>
        <br/>
        <span class="meeting">{{meeting_text}}</span>
        </li>
    {{/courses}}
    </ul>
    </div>

And the result would look like:

Copyright © David Heitmeyer