简体   繁体   English

把手增加了课程

[英]Handlebars add class

I have following JSON: 我有以下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: 我正在使用这样的把手来生成li:

     <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. 我很感激有人可以对此有所了解。

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. available列表中标记selected日期,以便在迭代期间对其进行测试。

  1. parse the JSON to an object 将JSON解析为对象
  2. iterate over the available list and compare the ids to the elements in selected 迭代available列表并将id与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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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