Skip to content

Instantly share code, notes, and snippets.

@simshaun
Created July 12, 2012 00:19
Show Gist options
  • Save simshaun/3094656 to your computer and use it in GitHub Desktop.
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 }}
<?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';
}
}
@simshaun
Copy link
Author

Sample YML definition (minus the "aFancyService" injection that you'd need if you had a fancy service to inject):

services:
    myhtml.twig.extension:
        class: S2\MyFancyBundle\Templating\MyHtmlExtension
        tags:
            -  { name: twig.extension }

@simshaun
Copy link
Author

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