twig-extension
Own Twig Extension
tip
Our DevTools Plugin does this!
Creating twig-extensions is very simple. First of all, create a folder in your Plugin/src folder. You can name this as you like, but for simplicity, we'll call it "TwigExtension". Create a new php file in it, too.
- src
- Twigextension
- MyTwigExtension.php
- Twigextension
Fill it with this template:
Click to expand
<?php
namespace <plugin>\TwigExtension;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class MyTwigExtension extends AbstractExtension
{
public function getFunctions()
{
return [
new TwigFunction('myMethod', [$this, 'myMethod'])
]
}
public function myMethod($value)
{
//do stuff
return $value;
}
}
?> To create a TwigFilter instead, you need to call the getFilters() instead. Here you add a new TwigFilter(). Other than that, it's the same Syntax!
Then, add your code and register the class in your services.xml. Here, you can also inject repositories and services!
<service id="<plugin>\TwigExtension\MyTwigExtension">
<tag name="twig.extension"/>
</service>
And that's it! Call it in Twig like this: {% myMethod(value) %}