php - How to Call Static Function In Symfony2 Twig Template -


how call static function in twig template without passing through controller?

for example:

... {{ mystaticclass::getdata() }} ... 

my static class:

class mystaticclass {     const v1 = 'value1';     const v2 = 'value2';     ...      public static function getdata() {         ...          return $data;     } } 

you cannot directly call php in twig template. you'll need create filter or function you're looking.

$twig         = new twig_environment($loader, $params); $twigfunction = new twig_simplefunction('mystaticclass', function($method) {     mystaticclass::$method }); $twig->addfunction($twigfunction); 

then in twig template do:

{{ mystaticclass('getdata') }} 

of course above example assumes mystaticclass within scope of wherever you're twig.

symfony example

you must create twig extentions. example below:

namespace purpleneve\web\pnwebbundle\extensions;  use purpleneve\web\pnwebbundle\dependencyinjection\currencyconverter;  class twigcurrency extends \twig_extension {     private $converter;      public function __construct(currencyconverter $converter)     {       $this->converter = $converter;     }      public function getname()     {         return 'currency';     }      public function getfilters()     {         return array(             'convertcurrency' => new \twig_filter_method($this, 'getconversionbetween')         );     }      public function getconversionbetween($amount, $isofrom, $isoto="usd")     {         try {           $value = $this->converter->convertamount($amount, $isofrom, $isoto);           return round($value,2);         } catch(\exception $e) {           return "?";         }     } } 

this example of extension created convert currency 1 currency in twig.

to implement it, need create service object in services.yml

parameters:     currency_converter.class: purpleneve\web\pnwebbundle\dependencyinjection\currencyconverter  services:     currency_converter:         class: "%currency_converter.class%"         arguments : [@doctrine.orm.entity_manager]      twig.extension.currency:         class: purpleneve\web\pnwebbundle\extensions\twigcurrency         tags:             - { name: 'twig.extension' }         arguments : [ @currency_converter ] 

then above, within twig can call class , function using {{ convertcurrency(55505, 'cad', 'usd) }}


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -