To see her, to love her!
HandleBars! loving it!

Usage:

{{!1.}}
<h1>{{title}}</h1>
<h1>{{article.title}}</h1>
<h1>{{article/title}}</h1>

{{!2.}}
{{{link "See more..." story.url}}}
{{{link story.text story.url}}}
{{{link "See more..." href=story.url}}}

{{!3.}}
{{#list people}}{{firstName}} {{lastName}}{{/list}}

{{!4.}}
<div>
{{! output author names }}
  {{#if author}}
    <h1>{{firstName}} {{lastName}}</h1>
  {{else}}
    <h1>Unknown Author</h1>
  {{/if}}
</div>

{{!5.}}
<div>
  {{! This comment will not be in the output }}
  <!-- This comment will be in the output -->
</div>

 

Working with ExpressJs:

Setting up a template engine is easier with Consolidate.
Make the package.json files with the following:

{
  "name": "project-name",
  "description": "Project Description",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "express": "3.x",
    "consolidate": "0.4.0",
    "handlebars": "1.0.x"
  }
}

 

Then run the following command from your project directory:

npm install

Using HandleBars

To configure handlebars to render .html views of the ./views/ folder you will just need to configure express using the consolidate helper:

// Use handlebars as template engine
app.engine("html", consolidate.handlebars);
app.set("view engine", "html");
app.set("views", __dirname + "/views");

Register partials

In handlebars you can use partials in your templates with {{> partial}}. If you want partials to work you must register them, you can use this simple hack to register all the templates found in ./views/partials/.

// Register partials
var partials = "./views/partials/";
fs.readdirSync(partials).forEach(function (file) {
    var source = fs.readFileSync(partials + file, "utf8"),
        partial = /(.+)\.html/.exec(file).pop();

    Handlebars.registerPartial(partial, source);
})

 

More detail example can be found on Gist.

Comments

comments