0

I have a collection named Sites like this:

{ site: "a", price: 100, currency: USD } { site: "b", price: 70, currency: EUR } { site: "c", price: 300, currency: CNY }

In my template I have:

{{#each sites}}
{{site}}
{price}}
{{/each}}

My helper does this:

Template.prices.sites = function() { return Sites.find(); };

The user is given a select option and I want to be able to show prices in a single currency according to the selection.

So If the user selects EUR, the price of the item: { site: "a", price: 100, currency: USD } will be displayed as price * eur_usd_exchange_rate

I can do this by creating individual template variables for each item and creating a different helper for each.

But I want to be able to use a single helper. How can I do this?

Emre Kenci
  • 2,715
  • 4
  • 26
  • 35

1 Answers1

1

I'd recommend creating a site template like so:

<template name="prices">
  {{#each sites}}
    {{> site}}
  {{/each}}
</template>

<template name="site">
  {{site}}
  {{price}}
</template>

This gives you access to this.price and this.currency in the helper:

Template.site.helpers({
  price: function() {
    var selectedCurrency = Session.get('currency');
    return this.price * exchangeRate(selectedCurrency, this.currency);
  }
});

This assumes the selected currency is stored in the currency session variable. Then all you have to do is implement the exchangeRate function and you should be all set.

David Weldon
  • 63,632
  • 11
  • 148
  • 146
  • Thank you. This worked. I need a better understanding of this argument though. – Emre Kenci Jan 18 '14 at 22:29
  • 1
    Inside of each iteration of `{{#each sites}}`, the context is a `site`. That context gets passed to each instance of the site template, so the template handlers have access to the site's data. If you walk through the [templates](http://docs.meteor.com/#templates) intro from the docs, and the [leaderboard example](https://www.meteor.com/examples/leaderboard), this may become more clear. – David Weldon Jan 18 '14 at 23:25
  • Thanks again. I've been trying to find a solution to another problem now. I have a sort by selection and on the helper I do "return Sites.find({}, {sort: {selected_sort_option: -1}});" but if I can't figure out how to sort the sites for price using their modified values. I should probably ask another question about it right? – Emre Kenci Jan 19 '14 at 00:44
  • Glad to be of help. Yeah I'd ask another question. That way the code can be properly formatted. – David Weldon Jan 19 '14 at 01:22