Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebarsjs check if a string is equal to a value

Is it possible in Handlebars to check if a string is equal to another value without registering a helper? I can't seem to find anything relevant to this in the Handlebars reference.

For example:

{{#if sampleString == "This is a string"}}
...do something
{{/if}}
like image 439
colmulhall Avatar asked Dec 13 '15 15:12

colmulhall


3 Answers

It seems you can't do it "directly"

Try use helper, why not?

Register helper in your javascript code:

Handlebars.registerHelper('ifEquals', function(arg1, arg2, options) {
    return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
});

Use in template:

{{#ifEquals sampleString "This is a string"}}
    Your HTML here
{{/ifEquals}}

More details here: Logical operator in a handlebars.js {{#if}} conditional

Update: Another way:

lets assume, your data is:

var data = {
    sampleString: 'This is a string'
};

Then (using jQuery):

$.extend(data, {isSampleString: function() {
    return this.sampleString ==  'This is a string';}
});

An use template:

{{#if isSampleString}}
    Your HTML here
{{/if}}
like image 78
Mihail Avatar answered Nov 15 '22 21:11

Mihail


The previous answer with match does not work for me, I get an error on the if statement (something like 'must have only one argument').

However, I just found the solution here without having to write any more helper:

{{#if (eq person "John")}} hello {{/if}}
like image 21
Kerhael Avatar answered Nov 15 '22 22:11

Kerhael


I would just use helpers like this:

Handlebars.registerHelper('ifeq', function (a, b, options) {
    if (a == b) { return options.fn(this); }
    return options.inverse(this);
});

Handlebars.registerHelper('ifnoteq', function (a, b, options) {
    if (a != b) { return options.fn(this); }
    return options.inverse(this);
});

Then in your code:

{{#ifeq variable "string"}} 
    ... do this ... 
{{/ifeq}}
{{#ifnoteq variable "string"}} 
    ... do this ... 
{{/ifnoteq}}
like image 19
Pablo Varando Avatar answered Nov 15 '22 22:11

Pablo Varando