2013-08-29 96 views
2

內枝杈我在樹枝過濾器:symfony2.3過濾器其它過濾

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; 
    } 
} 

但如何可以調用其他過濾器內的價格過濾器?在symfony 2.0中聲明過濾器使用'price' => new \Twig_Filter_Method($this, 'priceFilter')

並且可以從另一個過濾器中調用它。

感謝和抱歉,我的英語

回答

5

,如果你想在其他過濾器到你的價格過濾器的返回值,你可以在樹枝把它們連:

{{ value|acme_filter|price }} 

或者在其他方向,如果您需要在其他過濾器的價格過濾器的返回值:

{{ value|price|acme_filter }} 

如果你真的需要的價格過濾器在你的其他過濾器中,沒問題。該擴展是一個普通的PHP類。

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

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

    // do something with $whatever 

    return $whatever; 
} 
0

您使用的回調函數爲「靜態」。

您可以定義功能爲靜態,或更換爲\ Twig_Filter_Method($此,「priceFilter」)

2
class SomeExtension extends \Twig_Extension { 
    function getName() { 
     return 'some_extension'; 
    } 

    function getFilters() { 
     return [ 
      new \Twig_SimpleFilter(
       'filterOne', 
       function(\Twig_Environment $env, $input) { 
        $output = dosmth($input); 
        $filter2Func = $env->getFilter('filterTwo')->getCallable(); 
        $output = call_user_func($filter2Func, $output); 
        return $output; 
       }, 
       ['needs_environment' => true] 
      ), 
      new \Twig_SimpleFilter(
       'filterTwo', 
       function ($input) { 
        $output = dosmth($input); 
        return $output; 
       } 
      ) 
     ]; 
    } 
}