Setup helpers for multiple field separated by comma in a single column in a table

Hi,

How do you setup the helper for a multiple fields comma separated in a single column in the table?

For example, I have a collection with three fields:

field1, field2, field3

My use case is to display it in the same column(td) on the table with comma “,” in between. The three fields are all optional, meaning, there’s a document with only field1.

Normally, we can do this by separating the three fields on each column and write a helper like this.

Template.myTemplate.helpers({
  column: function(){
    return Collection.find();
  }
});

in template:

<template name="myTemplate">
  {{#each column}}
   <td>{{ field1 }}</td>
   <td> {{ field2 }}</td>
   <td> {{ field3 }}</td>
  {{/each}}
</template>

my use case is like this:

<template name="myTemplate">
  {{#each column}}
   <td>{{ field1 }}, {{ field2 }}, {{ field3 }}</td>
  {{/each}}
</template>

The problem in this set up is what if there’s no data in field2 and Field3, so the column will look like this:

data1, , ,

How do you set up the helper where the comma “,” will appear if it has two or more fields?

Thanks.

I use CSS sometimes for this - https://gist.github.com/jedsundwall/586144

Or, you could make a helper for each field that checks if the next field exists, and appends a comma to it if it does.

Inside a helper, you can access the current data context with this. So you can just create a helper like:

pickFields() {
  // put the object's fields values in an array
  const columnValues = Object.keys(this).map((key) => {
    return this[key];
  });

  return columnValues.join(', ');
}

Then call it from your template:

<template name="myTemplate">
  {{#each column}}
   <td>{{pickFields}}</td>
  {{/each}}
</template>

You’ll probably need to tweak it for your case, but it’s a start.

Thanks @energistic for the insights and @kako for the useful pattern!