How to get count of array in template?

I have documents like this:

{
   "_id": "asd4232sd",
   "title": "This is a title",
   "viewers": [
      "as429r23",
      "asd40005",
      "sk4929sdf"
   ]
}

I then display all of them in an {{#each}}. Is there an easy way to display just the count of fields in the viewers array in my template? Something like:

{{#each}}
    {{title}} - Number of Viewers:  {{viewers.count}}
{{/each}}

I’m using Blaze and Flow Router.

You should create a helper for this

{{#each}}
    {{title}} - Number of Viewers:  {{viewersCount viewers}}
{{/each}}
Template.yourTemplateName.helpers({
viewersCount : function(viewer){
return : (viewer.length || 0);
}
});
1 Like

{{../length}} or some variation thereof should work too. I’m not at my computer so can’t test it but I’m pretty sure length is a standard property and .. gives you the parent context.

Perfect! This is exactly what I needed. Thank you for the help.

1 Like

Thanks, It works for me.

1 Like