diff --git a/ETwigViewRenderer.php b/ETwigViewRenderer.php index d460392..61ab417 100644 --- a/ETwigViewRenderer.php +++ b/ETwigViewRenderer.php @@ -1,4 +1,4 @@ -_twig->addGlobal('App', $app); + + //Adding PHP-global functions + $this->_twig->addGlobal('php', new ETwigViewRendererPhpGlobal()); // Adding Yii's core static classes proxy as 'C' shortcut (usage: {{C.Html.tag(...)}}) $this->_twig->addGlobal('C', new ETwigViewRendererYiiCoreStaticClassesProxy()); @@ -223,6 +226,7 @@ public function getTwig() private function _addCustom($classType, $elements) { $classFunction = 'Twig_'.$classType.'_Function'; + $simpleClass = 'Twig_Simple'.$classType; foreach ($elements as $name => $func) { $twigElement = null; @@ -236,10 +240,15 @@ private function _addCustom($classType, $elements) case is_array($func) && is_string($func[0]) && isset($func[1]) && is_array($func[1]): $twigElement = new $classFunction($func[0], $func[1]); break; + // Callback given + case is_callable($func): + $twigElement = new $simpleClass($name, $func); + break; } if ($twigElement !== null) { - $this->_twig->{'add'.$classType}($name, $twigElement); + if($twigElement instanceof Twig_SimpleFunction || $twigElement instanceof Twig_SimpleFilter) $this->_twig->{'add'.$classType}($twigElement); + else $this->_twig->{'add'.$classType}($name, $twigElement); } else { throw new CException(Yii::t('yiiext', 'Incorrect options for "{classType}" [{name}]', @@ -320,4 +329,18 @@ function __get($className) function ETwigViewRendererVoidFunction($argument) { return ''; +} + +/** + * Class-wrapper of PHP-global functions + * + * @author Dmitry Morgachev + * @version 1.0.0 + */ +class ETwigViewRendererPhpGlobal +{ + function __call($func, $args=array()) + { + return call_user_func_array($func, $args); + } } \ No newline at end of file diff --git a/README.md b/README.md index 7ee9e0f..fde1c47 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -Twig view renderer +Twig view renderer ================== This extension allows you to use [Twig](http://twig.sensiolabs.org) templates in Yii. @@ -69,4 +69,28 @@ This extension allows you to use [Twig](http://twig.sensiolabs.org) templates in ] }, true) }} +``` + +###Callbacks usage example +```php +'viewRenderer' => array( + 'class' => 'ext.ETwigViewRenderer', + 'filters' => array( + 't' => function($message, $options = array(), $category = 'app'){ + return Yii::t($category, $message, $options); //change places of arguments + } + ), + 'functions' => array( + 'route' => function($route) { + return Yii::app()->urlManager->createUrl($route); //use non-static methods + } + ) +), +``` + +Than you can do that: + +```html +

{{ 'Hello, world!'|t }}

+{{ 'Home'|t }} ``` \ No newline at end of file