Bicu Bicu - 3 months ago 20
Twig Question

symfony2.3 filter twig inside other filter

i have filter in twig :

class AcmeExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('price', array($this, 'priceFilter')),
);
}

public function priceFilter($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',')
{
$price = number_format($number, $decimals, $decPoint, $thousandsSep);
$price = '$'.$price;

return $price;
}
}


but how can call price filter inside other filter? in symfony 2.0 declared filter with
'price' => new \Twig_Filter_Method($this, 'priceFilter')


and could from within another filter call this.

thanks and sorry for my english

Answer

if you want the returned value of the other filter into your price filter, you can chain them in twig:

{{ value|acme_filter|price }}

Or in the other direction, if you need the return value of the price filter in your other filter:

{{ value|price|acme_filter }}

If you really need the price filter inside your other filter, no problem. The extension is a plain php class.

public function acmeFilter($whatever)
{
    // do something with $whatever

    $priceExtentsion = new PriceExtenstion();
    $whatever = $priceExtension->priceFilter($whatever);

    // do something with $whatever

    return $whatever;
}