问题描述
我有一个名为 Sites 的集合,如下所示:
I have a collection named Sites like this:
{ 站点:a",价格:100,货币:美元 }{ 站点:b",价格:70,货币:欧元 }{ 站点:c",价格:300,货币:CNY }
{ site: "a", price: 100, currency: USD }{ site: "b", price: 70, currency: EUR }{ site: "c", price: 300, currency: CNY }
在我的模板中,我有:
{{#each sites}}
{{site}}
{price}}
{{/each}}
我的助手这样做:
Template.prices.sites = function(){返回 Sites.find();};
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.
所以如果用户选择了 EUR,商品的价格:{ site: "a", price: 100, currency: USD } 将显示为 price * eur_usd_exchange_rate
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?
推荐答案
我建议像这样创建一个 site
模板:
I'd recommend creating a site
template like so:
<template name="prices">
{{#each sites}}
{{> site}}
{{/each}}
</template>
<template name="site">
{{site}}
{{price}}
</template>
这使您可以访问帮助程序中的 this.price
和 this.currency
:
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);
}
});
这假定所选货币存储在 currency
会话变量中.然后你所要做的就是实现 exchangeRate
函数,你应该一切都准备好了.
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.
这篇关于如何单独修改和显示集合中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!