0

I want to create an unordered list based on an array of objects using Handlebars JS.

The objects take the following form:

{ name: 'NameOne', id: 001, category: 2 }, { name: 'NameTwo', id: 002, category: 1 }, { name: 'Name Three', id: 003, category: 1 }, { name: 'Name Four', id: 004, category: 3 }...

At the moment I have a template with an each function which compiles an UL with each object making a new list item, as so:

{{#each this}}
    <li>{{ name }}</li>
{{/each}}

What I would like to do is find the simplest way to divide the list depending on categories, so I could end up with something like this...

Category 1
    NameTwo
    NameThree
Category 2
    Name One
Category 3
   Name Four

If I can do this only with the template, that would be perfect, but I can also change the JS which compiles the template if needed. I would also be open for using EJS templates if that is a better solution. I have thought of a couple of solutions, but all seem very over-complicated and don't work very well, but surely this can be quite a common problem and there must be good solutions.

Many thanks.

Jack Wild
  • 2,072
  • 6
  • 27
  • 39

1 Answers1

2

Hi when I'm solving problems like this, I tend to manipulate the data though JavaScript to keep the template clean.

How about trying something like this:

HTML

{{#each list}} 
  <ul>
      <li>
          Category {{@key}}
          <ul>
              {{#each this}}
                  <li>{{name}}</li>
              {{/each}}
          </ul>
      </li> 
  </ul>     
{{/each}} 

JS

var rawData = [
    { name: 'NameOne', id: 001, category: 2 }, 
    { name: 'NameTwo', id: 002, category: 1 }, 
    { name: 'Name Three', id: 003, category: 1 }, 
    { name: 'Name Four', id: 004, category: 3 }
]; 

var data = {
    list:{

          }
};

for (var i = 0; i < rawData.length ; i++) {

    var a = rawData[i];
    var cat = a.category;

    if(typeof data['list'][cat] === 'undefined'){
        data['list'][cat] = [];
    }
    data['list'][cat].push(a);
 }

Also here is a jsfiddle

  • Thanks, very helpful. I just moved the start and end ul tags out of the each loop so that it was all in one list which is what I need. Then embedded lists for categories works well. Thought there might have been a simple way to do this just in the template without sorting the rawData first, but seems not. – Jack Wild Oct 21 '14 at 12:22