Created
July 12, 2012 00:19
-
-
Save simshaun/3094656 to your computer and use it in GitHub Desktop.
Simple Twig extension that provides a new function and filter for templates, {{ get_some_html() }} {{ 5500|price }}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace S2\MyFancyBundle\Templating; | |
use Symfony\Component\DependencyInjection\ContainerInterface; | |
class MyHtmlExtension extends \Twig_Extension | |
{ | |
private $aFancyService; | |
public function __construct($aFancyService) | |
{ | |
$this->aFancyService= $aFancyService; | |
} | |
public function getFunctions() | |
{ | |
return array( | |
'get_some_html' => new \Twig_Function_Method($this, 'getSomeHtml', array('is_safe' => array('html'))), | |
); | |
} | |
public function getFilters() | |
{ | |
return array( | |
'price' => new \Twig_Filter_Method($this, 'priceFilter'), | |
); | |
} | |
public function getSomeHtml() | |
{ | |
return $this->aFancyService->getTheHtml(); | |
} | |
public function priceFilter($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',') | |
{ | |
$price = number_format($number, $decimals, $decPoint, $thousandsSep); | |
$price = '$' . $price; | |
return $price; | |
} | |
public function getName() | |
{ | |
return 'a_fancy_name'; | |
} | |
} |
Sample XML definition (minus the "aFancyService" injection that you'd need if you had a fancy service to inject):
<service id="myhtml.twig.extension" class="S2\MyFancyBundle\Templating\MyHtmlExtension">
<tag name="twig.extension" />
</service>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample YML definition (minus the "aFancyService" injection that you'd need if you had a fancy service to inject):