how to display names in alphabetical groups in Handlebarsjs underscorejs

后端 未结 2 1832
无人共我
无人共我 2021-02-06 18:44

Hi am New to Handlebarsjs.

I have a collection of contacts with name, email, phone, etc. as below

[
  {
    \"name\": \"Bob Wolmer\",
    \"email\": \"bo         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-06 19:23

    First you need to define the Handlebars Template that suits your JSON layout;

    {{#list people}}{{name}} {{email}} {{phone}} {{address}} {{contactId}} {{labels}}{{/list}}
    

    I assume people is the name of your JSON list like this;

    { people: [
      {
        "name": "Bob Wolmer",
        "email": "bob@wolmer.com",
        "phone": "(535) 235-1234",
        "address": "301 Cobblestone Wy., Berdrock 00000",
        "contactId": "1121",
        "labels": {}
      },
      {
        "name": "Wilma Erra",
        "email": "wilma@erra.com",
        "phone": "(535) 235-3659",
        "address": "301 Cobblestone Wy., Berdrock 70777",
        "contactId": "1122",
        "labels": {}
      },
      {
        "name": "Brad",
        "email": "brad@brad.com",
        "phone": "(535) 235-3546",
        "address": "301 Cobblestone Wy., Redrock 70777",
        "contactId": "1123",
        "labels": [{"name": "Friends"},{"name": "Family"}]
      },
      {
        "name": "",
        "email": "wilson@gmail.com",
        "phone": "(535) 235-3657",
        "address": "301 Cobblestone Wy., Dedrock 70777",
        "contactId": "1124",
        "labels": [{"name": "Friends"}]
      }
    ]}
    

    Then you can register your list Handlebars template using like this and iterate through your JSON;

    Handlebars.registerHelper('list', function(items, options) {
      var out = "
      "; var names = []; var letters = []; for(var i=0, l=items.length; i" + letters[i] + ""; for(var k=0; k < names[letters[i]].length; k++){ out = out + "
    • " + names[letters[i]][k] + "
    • "; } } return out + "
    "; });

    The output is;

    • B
    • Bob
    • Brad
    • W
    • Wilma

提交回复
热议问题