brainless
brainless

Reputation: 5819

How to check for empty-string, null or white-spaces in handlebar?

I need to check for null values, empty-strings and strings with whitespaces only and substitute them with "No Content".

I tried this but it worked only for null and empty string not for whitespaces-only strings.

{{#if value}}
    {{value}}
{{else}}
    <p>No Content</p>
{{/if}}

How to do it? Is helpers the only option?

Upvotes: 10

Views: 25664

Answers (2)

76484
76484

Reputation: 9003

As you have alluded to in your question, a String with a non-zero length, even if it contains only space characters, is Truthy in JavaScript. This is why a String of whitespace characters will match the {{if value}} case in your template and render the value instead of rendering the {{else}} case.

As yours is a special case where you want to treat Strings of only whitespace characters the same as empty, null and undefined, you will need to create a custom Handlebars Helper.

One way you could do the evaluation in your helper would be to use a Regular Expression to remove all whitespace characters and then check the length of the result. The helper could look like:

Handlebars.registerHelper('ifEmptyOrWhitespace', function (value, options) {
    if (!value) { return options.fn(this); }
    return value.replace(/\s*/g, '').length === 0
        ? options.fn(this)
        : options.inverse(this);
});

I have created a fiddle for reference.

Upvotes: 1

e-israel
e-israel

Reputation: 646

This is a useful Helper.

Handlebars.registerHelper('check', function(value, comparator) {
    return (value === comparator) ? 'No content' : value;
});

Tests template

{{#check value ""}}
  {{this}}
{{/check}}

{{#check value null}}
  {{this}}
{{/check}}

{{#check value undefined}}
  {{this}}
{{/check}}

Upvotes: 3

Related Questions