Templating(with HandleBars)

Context Objects

When a template is rendered using res.render, there are two arguments. →

The view or template to render… and the context object.

The context object's properties are available to your template as variable names!

// the second argument is an object
res.render('myview', {'item':'pizza', 'description':'tasty'});
<h3>{{ description }} {{ item }}</h3>
<h3>tasty pizza</h3>
 

Ok… Variables Make Sense

Just use double curly braces (no spaces) to drop a value in your context into your template!

But what about some logic. What if the value that I'm passing in is an array or object? →

Handlebars actually has some basic facilities for:

  • looping
  • conditionals
  • …and other structures

Block Expressions / Helpers

From the handlebars docs

Block expressions allow you to define helpers that will invoke a section of your template with a different context than the current

  • …errr … basically, that means you'll be able to add control structures to your templates, like conditionals and iteration.
  • use double curly braces, but prefix your helper with a hash… and make sure you close it at the end
  • {{#helper}}stuff{{/helper}}
  • notice that there are no spaces!
 

Looping Over Arrays Example

The #each helper:

  • allows you iterate over a series of items
  • within #each, you can use {{this}} or {{.}} to output the current item


In your application: →

app.get('/templating-arrays', function(req, res) {
	res.render('templating-arrays', {'luckyNumbers':[42, 7, 78, 3, 5]});
});

In your view: →

<ul>
{{#each luckyNumbers}}
	<li>{{this}}</li>
{{/each}}
</ul>
 

Dealing with an Array of Objects

Assuming this context object (points is an Array of objects):

{points: [{x:1, y:2, z:3}, {x:21, y:34, z:55}]}

Use dot notation to access properties:

<ul>
{{#each points}}
<li>{{this}}, {{this.x}}, {{this.y}}, {{this.z}} </li>
{{/each}}
</ul>

Or just the property name!

<ul>
{{#each points}}
<li>{{x}}, {{y}}, {{z}}</li>
{{/each}}
</ul>
 

Conditionals

(Note - no equality operators 4 U) …

{{#if isActive}}
  <img src="star.gif" alt="Active">
{{else}}
  <img src="cry.gif" alt="Inactive">
{{/if}}
 

Template Error?

By the way, if you see something like:

Expecting 'ID', 'DATA', got 'INVALID'

You probably have spaces in your {{ #helper }}.

 

 
posted @ 2023-03-02 00:00  M1stF0rest  阅读(20)  评论(0编辑  收藏  举报