Using customer function in Twig

My computer develop environment

1
2
3
4
5
"require": {
"php": ">=5.6.10",
"symfony/symfony": "2.8.*",
...
}

For example, i want to replace the string in twig
First, you should add a twig extension under your bundle

1
2
3
$ tree -l src/AppBundle/Twig/
src/AppBundle/Twig/
└── Preg.php

And the php file content look like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
namespace AppBundle\Twig;

class Preg extends \Twig_Extension
{
public function getFilters()
{
return [
new \Twig_SimpleFilter('preg',[
$this,
'contentReplace'
])
];
}

public function contentReplace($content,$search, $replace)
{
return preg_replace($search,$replace,$content);
}
}

Then modify the config/services.yml to add the new method to system’s service

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Learn more about services, parameters and containers at
# http://symfony.com/doc/current/book/service_container.html
parameters:
# parameter_name: value

services:
# service_name:
# class: AppBundle\Directory\ClassName
# arguments: ["@another_service_name", "plain_value", "%parameter_name%"]
...
preg.twig_extension:
class: AppBundle\Twig\Preg
public: false
arguments: []
tags:
- { name: twig.extension }

After these steps, you can use the method called ‘preg’ defined by Preg.php in the twig template file.

1
2
3
4
5
6
7
<div class="panel-body">
<div class="well">
<p>
{{ exception.getMessage|preg("/.*lilyuliang'blog/",'') }}
</p>
</div>
</div>

Share