Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebars #if and numeric zeroes

In my Handlebars template I check for the existence of a variable, and render some text if it's there:

{{#if foo}}
  some text
{{/if}}

This works fine if foo is text or if foo is numeric but not zero. But if

var foo = 0;

then {{#if foo}} returns false.

This appears to be yet another Javascript oddity, because Javascript itself behaves the same way. In Javascript code, though, you could get around this by checking if the variable is 'undefined'.

How can I do the same thing in Handlebars?

I could write an {{#exists}} helper, but I was hoping there was something built in.

like image 923
ccleve Avatar asked Jun 13 '13 19:06

ccleve


People also ask

What is Handlebars used for?

Handlebars is a simple templating language. It uses a template and an input object to generate HTML or other text formats. Handlebars templates look like regular text with embedded Handlebars expressions. A handlebars expression is a {{ , some contents, followed by a }} .

How do you define Handlebars?

Definition of handlebar : a straight or bent bar with a handle at each end specifically : one used to steer a bicycle or similar vehicle —usually used in plural.

What are Handlebars in node?

Handlebars. js is a templating engine similar to the ejs module in node. js, but more powerful and simple to use. It ensures minimum templating and is a logicless engine that keeps the view and the code separated. It can be used with express as the hbs module, available through npm.

Is Handlebars one or two words?

Usually handlebars. the curved steering bar of a bicycle, motorcycle, etc., placed in front of the rider and gripped by the hands.


3 Answers

There is something built in for this:

{{#if foo includeZero=true}}
    foo!
{{/if}}

This displays foo! when foo is 0.

like image 177
albertjan Avatar answered Sep 30 '22 01:09

albertjan


I would go one better and provide a case for the {{else}} condition...

/**
 * The {{#exists}} helper checks if a variable is defined.
 */
Handlebars.registerHelper('exists', function(variable, options) {
    if (typeof variable !== 'undefined') {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});

Now you can have:

{{#exists myvar}}
  <p>Value of myvar is ... {{myvar}}</p>
{{else}}
  <p>Please supply a myvar</p>
{{/exists}}
like image 45
Shane Avatar answered Sep 30 '22 00:09

Shane


I just went ahead and wrote an {{#exists}} helper. But if someone has a better solution, please post it.

/**
 * The {{#exists}} helper checks if a variable is defined.
 */
Handlebars.registerHelper('exists', function(variable, options) {
    if (typeof variable !== 'undefined') {
        return options.fn(this);
    }
});
like image 22
ccleve Avatar answered Sep 29 '22 23:09

ccleve