Typically in Meteor templates, if you supply data through a router like iron-router, you are returning a set of documents (really a cursor) that you iterate through with the #each operator. But what if you only want to return a specific element from some field that is an array? I've tried several things, including the $slice operator in my query, but nothing seems to work.
1 Answer
Here is a simple route that sets data to an array:
Router.map(function() {
this.route('home', {
path: '/',
template: 'home',
data: [{fruit: 'apples', count: 10}, {fruit: 'oranges', count: 5}]
});
});
The home template looks like this:
<template name="home">
<p>{{snack.fruit}}: {{snack.count}}</p>
</template>
To show 'apples' as the snack, you need only access the first element of this:
Template.home.helpers({
snack: function() {
return this[0];
}
});
Note, however, that this inside of the helpers is not actually an array - it will be an object with the same key-value pairs as the data you supplied (as well as a yield function apparently).
3 Comments
Michael McC
Great. That would have taken me some time to figure out. I should be able to make this work. Just out of curiosity, is it possible pass a parameter to that template helper in a case like this? Would {{snack.fruit parameter}} work?
David Weldon
No you can't pass parameters to your template helpers. You can pass parameters to a handlebars helper, e.g.
{{formatSnackCount snack.count}} where formatSnackCount has been registered with Handlebars.registerHelper.ConorLuddy
Thanks for this! Another nugget of clarity while learning the basics of Meteor :)
dataand show element n"? Or are you asking something about loading data from the DB and showing only a single field? I can't really tell without code or more explanation.return this['myData'][1];console.log(this)to the first line of your helper. That's a quick way to see the structure you need to access.