Handlebars

Sept 20, 2022

Handlebars

Views

Handlebars are template files that consist of HTML plus Handlebars markup for additional functionality. These files will be used by res.render() calls in route definitions.

layout.hbs

The layout.hbs file provides the layout template for all other views. Anything that should be in all views will be contained here (like the general HTML skeleton or a navbar).

Placeholders

Placeholders

Local variables can be passed into views, via res.render()

Route

res.render('index', { title: 'CSE 252' , name: 'Don' });

Handlebars

<h1>{{title}}</h1>
<p>Welcome, {{name}}!</p>

Rendered HTML

<h1>CSE 252</h1>
<p>Welcome, Don!</p>

conditional Logic

conditional Logic

The {{#if}} helper can provide for conditional display of content in views. Note that you cannot use conditional operators in the test; you can only provide a variable that will evaluate to truthy/falsey

{{#if user}}
    Welcome, {{user}}!
{{else}}
    <a href="/login">Login Here</a>
{{/if}}

looping

looping

The {{#each}} helper can provide iteration in views

Route

const people = [ 'Joe', 'Erin', 'Pat'];
res.render('people-list', { people });

Handlebars

<h1>People List</h1>
{{#each people}}
    <h2>{{this}}</h2>
{{/each}}

Rendered HTML

<h1>People List</h1>
<h2>Joe</h2>
<h2>Erin</h2>
<h2>Pat</h2>

object looping

object looping

If the looped variable is an array of objects, you can directly reference property names.

Route

const people = [ { firstName: 'Jess' }, { firstName: 'Fred' }]];
res.render('people-list', { people });

Handlebars

<h1>People List</h1>
<table>
{{#each people}}
    <tr><td>{{firstName}}</td></tr>
{{/each}}
</table>

Rendered HTML

<h1>People List</h1>
<table>
    <tr>
        <td>Jess</td>
    </tr>
    <tr>
        <td>Fred</td>
    </tr>
</table>