RuntimeException
RuntimeException

Reputation: 1135

Handlebars add class

I have following JSON:

 "daysRange": {
    "status": "UNSPECIFIED/ALL/SPECIFIED",
    "available": [
      {
        "id": "1",
        "name": "MONDAY"
      },
      {
        "id": "2",
        "name": "TUESDAY"
      },
      {
        "id": "3",
        "name": "WEDNESDAY"
      },
      {
        "id": "4",
        "name": "THURSDAY"
      },
      {
        "id": "5",
        "name": "FRIDAY"
      },
      {
        "id": "6",
        "name": "SATURDAY"
      },
      {
        "id": "7",
        "name": "SUNDAY"
      }
    ],
    "selected": [
      {
        "id": "2",
        "name": "TUESDAY"
      }
    ]
  }

I'm using handlebars like this to generate li's:

     <ul class="available">
        {{#each daysRange.available}}
          <li data-id="{{this.id}}">{{this.name}}</li>
        {{/each}}
     </ul>  

Question: How can I add class selected to selected days? I'll appreciate is someone can shed some light on this.

Upvotes: 0

Views: 4946

Answers (1)

Evan Davis
Evan Davis

Reputation: 36592

You need to massage the data before it hits the template. Mark the selected day in the available list so you can test for it during the iteration.

  1. parse the JSON to an object
  2. iterate over the available list and compare the ids to the elements in selected
  3. something like

    if (available[i].id === selected[j].id) 
        available[i].selected = true;`
    

You can also do it with a custom helper, but this seems messier to me than just correcting your data:

Handlebars.registerHelper('isSelected', function(selected, options) {
    var ret = "";      
    if (this.id === selected[0].id) {
        ret = "selected";
    }
    return options.fn(ret);
});

then in your template,

 <ul class="available">
     {{#each daysRange.available}}
         <li data-id="{{this.id}}" class="{{#isSelected ../daysRange.selected}}{{this}}{{/isSelected}}">{{this.name}}</li>
     {{/each}}
 </ul> 

Upvotes: 2

Related Questions