Sept 20, 2022
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.
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).
Local variables can be passed into views, via res.render()
res.render('index', { title: 'CSE 252' , name: 'Don' });
<h1>{{title}}</h1>
<p>Welcome, {{name}}!</p>
<h1>CSE 252</h1>
<p>Welcome, Don!</p>
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}}
The {{#each}} helper can provide iteration in views
const people = [ 'Joe', 'Erin', 'Pat'];
res.render('people-list', { people });
<h1>People List</h1>
{{#each people}}
<h2>{{this}}</h2>
{{/each}}
<h1>People List</h1>
<h2>Joe</h2>
<h2>Erin</h2>
<h2>Pat</h2>
If the looped variable is an array of objects, you can directly reference property names.
const people = [ { firstName: 'Jess' }, { firstName: 'Fred' }]];
res.render('people-list', { people });
<h1>People List</h1>
<table>
{{#each people}}
<tr><td>{{firstName}}</td></tr>
{{/each}}
</table>
<h1>People List</h1>
<table>
<tr>
<td>Jess</td>
</tr>
<tr>
<td>Fred</td>
</tr>
</table>