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.
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 }} .
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.
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.
Usually handlebars. the curved steering bar of a bicycle, motorcycle, etc., placed in front of the rider and gripped by the hands.
There is something built in for this:
{{#if foo includeZero=true}}
foo!
{{/if}}
This displays foo!
when foo
is 0
.
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}}
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With