$app->register(new Silex\Provider\TwigServiceProvider(), array( 'twig.path' => __DIR__.'/../src/Views', 'twig.options' => array( 'charset' => 'utf-8', 'strict_variables' => true, 'cache' => __DIR__.'/cache' ) )); $app->before(function() use($app) { $app['twig']->addExtension(new \Twig\MyExtension($app)); }); |
<?php namespace Twig; class MyExtension extends \Twig_Extension { public function getName() { return 'my'; } public function getFilters() { return array( 'link' => new \Twig_Filter_Method($this, 'link_filter', array('is_safe' => array('html'))), ); } public function link_filter($ressource, $type = null) { $img_regex = '#(gif|jpe?g|png)$#i'; $url_regex = '#^(https?:\/\/)#i'; if(!$type) { if(preg_match($img_regex, $ressource)) { $type = 'img'; } else if(preg_match($url_regex, $ressource)) { $type = 'a'; } } switch($type) { case 'img': return '<img src="'.$ressource.'"/>'; break; case 'a': return '<a href="'.$ressource.'">'.$ressource.'</a>'; break; default: return $ressource; } } } |
<p>
{{ ressource|link }}
</p> |