Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

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!