我在一个twig扩展中使用intl组件来获取货币的符号。
非常简单,因为它得到了很好的解释here。
但我想做的是根据货币/本地格式化价格。
在intl组件(NumberFormatter class)
中确实存在一种方法formatCurrency<?php
namespace SE\AppBundle\Twig;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Intl\Intl;
class PriceExtension extends \Twig_Extension
{
private $em;
private $requestStack;
public function __construct(EntityManager $em, RequestStack $requestStack)
{
$this->em = $em;
$this->requestStack = $requestStack;
}
public function getFilters()
{
return array(
new \Twig_SimpleFilter('price', array($this, 'priceFilter')),
);
}
public function priceFilter($price)
{
$request = $this->requestStack->getCurrentRequest();
$currency_code = $request->cookies->get('currency');
$exchange_rate = $this->em->getRepository('ApiBundle:ExchangeRates')->findOneBy(array('code' => $currency_code));
$price = $price*$exchange_rate->getRate();
// Get the currency symbol
// $symbol = Intl::getCurrencyBundle()->getCurrencySymbol($currency_code);
// $price = $symbol.$price;
// Undefined formatCurrency method
$price = Intl::getCurrencyBundle()->formatCurrency($price, $currency_code);
return $price;
}
public function getName()
{
return 'price_extension';
}
}
我怎么能使用formatCurrency方法?
答案 0 :(得分:1)
对于尚未安装Intl Component的情况,整个intl
extension只是替换图层。
所以你的代码应该是这样的:
<?php
namespace SE\AppBundle\Twig;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Intl\NumberFormatter\NumberFormatter;
class PriceExtension extends \Twig_Extension
{
private $em;
private $requestStack;
public function __construct(EntityManager $em, RequestStack $requestStack)
{
$this->em = $em;
$this->requestStack = $requestStack;
}
public function getFilters()
{
return array(
new \Twig_SimpleFilter('price', array($this, 'priceFilter')),
);
}
public function priceFilter($price)
{
$request = $this->requestStack->getCurrentRequest();
$currency_code = $request->cookies->get('currency');
$exchange_rate = $this->em->getRepository('ApiBundle:ExchangeRates')->findOneBy([
'code' => $currency_code
]);
$price = $price*$exchange_rate->getRate();
if(false === extension_loaded('intl')) {
$formatter = new NumberFormatter('en', NumberFormatter::CURRENCY);
} else {
$formatter = new \NumberFormatter(
$request->getLocale(),
\NumberFormatter::CURRENCY
);
}
return $formatter->formatCurrency($price, $currency_code);
}
public function getName()
{
return 'price_extension';
}
}