简体   繁体   中英

If equals validate in handlebar template inside each loop

I have a php array like this one

bookings[] = {"arrived","cancelled","departed"};

When display this array in handlebars template i want to check IF equal condition.

In the following example when value is equals to cancelled i want to display some text.

{{#each bookings}}
    {{#if this.value cancelled}}
        cancelled
    {{/if}}
{{/each}}

This code is not working. What is alternative IF equals condition for handlebars to execute in loop.

Now my code is working,

bookings = ["arrived", "cancelled", "departed"];

Handlebar function:

 Handlebars.registerHelper('check_status', function(val1, val2) {
    return val1 === val2;
 });

Handlebar template:

 {{#if (check_status this 'cancelled')}} 

If I'm not mistaken you can't do an actual conditional in handlebars, you can only do if true/false which means that the **value** in {{#if **value**}} need to either be true or false

So what you will want to do is in the area of code where this.value is defined create a function like this

valueIsCancelled =  function(value) {
  return value === 'cancelled';
}

In your template you will do:

        {{#each bookings}}
         {{#if this.valueIsCancelled this.value}}
               cancelled
         {{/if}}
        {{/each}}  

or another option is to define another variable where value is defined that would be a boolean

var isCancelled = value === 'cancelled';

and your template would look like this

        {{#each bookings}}
         {{#if this.isCancelled}}
               cancelled
         {{/if}}
        {{/each}}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM