We're going to encrypt a value with a custom twig extension in the example below. No parameter can be passed to this extension.


Extension Class


# sport/src/Football/FrontendBundle/Twig/EncryptExtension.php
namespace Football\FrontendBundle\Twig;

use Twig_Extension;
use Twig_SimpleFilter;

class EncryptExtension extends Twig_Extension
{
public function getName()
{
return 'encrypt_extension';
}

public function getFilters()
{
return array(
new Twig_SimpleFilter(
'encrypt',
array($this, 'encryptFilter')
)
);
}

public function encryptFilter($value)
{
return sha1($value);
}
}

Config


# sport/src/Football/FrontendBundle/Resources/config/services.yml
services:
football_frontend.twig.extension.encrypt:
class: Football\FrontendBundle\Twig\EncryptExtension
public: false
tags:
- { name: twig.extension }

Twig


Assuming that name variable is set in default controller and carries "inanzzz" as its value.


Hello {{ name }}!
<br />
Hello {{ name|encrypt }}!

Test


If you call http://sport.local/app_dev.php in your browser, you should see output below.


Hello inanzzz! 
Hello bae9e624ee464e275fa804d047955bcc08caab5b!