How can I reuse code (html + handlebars) in assemble to show categorized lists?

StackOverflow https://stackoverflow.com/questions/22950064

  •  30-06-2023
  •  | 
  •  

Question

I'm using assemble

For example, if I have this data:

   {"people": [
        {
            "name": "Sally",
            "group": "A"
        },
        {
            "name": "John",
            "group": "B"
        },
        {
            "name": "Jane",
            "group": "B"
        },
        {
            "name": "Skippy",
            "group": "A"
        }
    ]}

How can I render two separate lists of names based on property values (A or B)?

Here is the desired html output:

<p>Group A</p>
<ul>
    <li>Sally</li>
    <li>Skippy</li>
</ul>

<p>Group B</p>
<ul>
    <li>John</li>
    <li>Jane</li>
</ul>

Currently, my handlebars template code looks like this. But, I want to avoid copying the same code again and again.

<p>Group A</p>
{{#each index.people }}
    {{#is group "A"}}
        {{ name }}: {{ group }}
    {{ /is }}
{{ /each }}
Était-ce utile?

La solution

The solution you're currently using is exactly what I would have recommended:

{{#each people}}
  {{#is group "A"}}
    ....
  {{/is}}
{{/each}}

However, you can easily create a handlebars helper to do whatever you want. e.g.

Handlebars.registerHelper('people', function (context, group) {
  return context.filter(function (item) {
    if (item.group) {
      return item.group === group;
    }
    return false;
  });
});

Now, given your list:

{
  "list": [
    {
      "name": "Sally",
      "group": "A"
    },
    {
      "name": "John",
      "group": "B"
    },
    {
      "name": "Jane",
      "group": "B"
    },
    {
      "name": "Skippy",
      "group": "A"
    }
  ]
}

you would use the helpers like this:

{{people list 'A'}}
{{people list 'B'}}

There is info on the assemble docs about how to register the helpers with assemble.

Autres conseils

How many groups do you actually have? If it's only a few, I would repeat the {{#each people}} loop a few times. I don't know of a way to do this without repeated markup using default assemble/handlebars methods.

If you have many groups, I might write a helper that takes that data and organizes it by group with 'people' lists inside. If you had data structured like this:

{"groups" : [
    {
        "groupName" : "A",
        "people" : [
            { 
                "name" : "Sally" 
            },
            { 
                "name" : "Skippy" 
            }
        ]
    },
    {
        "groupName" : "B",
        "people" : [
            { 
                "name" : "John" 
            },
            { 
                "name" : "Jane" 
            }
        ]
    }
]}

You could generate the markup with:

{{#each index.groups}}
    <p>Group: {{groupName}}</p>
    <ul>
        {{#each people}}
            <li>{{name}}</li>
        {{/each}}
    </ul>
{{/each}}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top