インド、米ドルなど、さまざまな通貨形式で金額を表示する Twig 拡張機能を作成しました。
Symfony2ガイドで提案されているように、次のようにしています。
NameSpace/AccountBundle/Extension/AccountExtension.php
namespace Edu\AccountBundle\Extension;
use Symfony\Component\HttpKernel\KernelInterface;
class AccountTwigExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
'get_money_indian_format' => new \Twig_Filter_Method($this, 'get_money_indian_format'),
);
}
function get_money_indian_format($amount, $suffix = 1) {
setlocale(LC_MONETARY, 'en_IN');
if (ctype_digit($amount) ) {
// is whole number
// if not required any numbers after decimal use this format
$amount = money_format('%!.0n', $amount);
} else {
// is not whole number
$amount = money_format('%!i', $amount);
}
if (!$suffix) {
return $amount;
} else {
return $amount;
}
return $amount;
}
public function getName()
{
return 'account_twig_extension';
}
}
に登録しましたapp/config/services.yml
:
account.twig.extension.accounttwigextension:
class: AccountBundle\Extension\AccountTwigExtension
tags:
- { name: twig.extension }
これを小枝ファイルで使用している場合:
{{ 50000 | get_money_indian_format }}
次のエラーが表示されます: The filter get_money_indian_format
does not exist inEduAccountBundle:Ledger:showLedgers.html.twig