Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to pass a parameter to Handlebars template in Meteor?

I am using Meteor 0.5.2 and trying to solve what seems to me is an obvious pattern that should have an easy solution.

I have a template that should return different chunk of data in each of template instances.

For example - I have a template showing TV program - show by show.

Then I need to display two instances of the same template with different data - one with past shows and one with upcoming shows.

So I have a tv program template:

<template name="tv_program">
   {{#each shows}}
   ...
</template>

Ideally I would like do something like:

{{> tv_program past_shows}}
...
{{> tv_program upcoming_shows}}

to pass a parameter to tv_program template instance that I can read from JavaScript and adjust the mongo queries.

Currently I have copy/pasted my template/js code and adjusted the mongo queries but there has to be a better way.

I looked into partials/helpers with arguments but that doesn't seem to be the solution to my problem.

Thanks, Vladimir

like image 460
vladimirp Avatar asked Jan 06 '13 18:01

vladimirp


Video Answer


1 Answers

You're approaching the problem at the wrong level. Rather than trying to tell your code what to do from your templates, you should tell your template what to do from your code. For instance:

Template.past_shows.shows = function() { return shows(-1); }

Template.upcoming_shows.shows = function() { return shows(1); }

function shows(order) {
  return Shows.find({}, {$sort: order});
}

<template name="past_shows">
  {{#each shows}}
    {{> show}}
  {{/each}}
</template>

<template name="upcoming_shows">
  {{#each shows}}
    {{> show}}
  {{/each}}
</template>

<template name="show">
  <li>{{_id}}: {{name}}</li>
</template>
like image 93
Rahul Avatar answered Oct 14 '22 13:10

Rahul