Creating a Custom Twig Function in a Shopware 6 Plugin
Published on Share
Imagine you want to call a PHP script within the Twig template during theme development, for example, to create an MD5 hash. For these cases, we can create our own Twig functions.
In this example, we pass a string to the Twig function and receive the MD5 hash as a return value.
It is not recommended to use Twig functions to retrieve data from the database. In such cases, a DataResolver might be helpful.
Prerequisites
To create your own Twig function for your plugin, you'll first need a plugin as a base. You can find a guide on how to create a plugin in the Shopware documentation.
Creating the Twig Function
To make the Twig function work, we need to create a few files—specifically, just two files: the PHP file with the Twig function itself and the services.xml
file. You probably already have the services.xml
.
For clarity, let's create a folder named Twig
within the src
directory. In that folder, we'll create a new PHP file. You can name it anything you like.
In the code, I refer to examples from the Shopware documentation. So, you need to replace SwagBasicExample
with your plugin name.
//<plugin root>/src/Twig/SwagCreateMd5Hash.php
<?php declare(strict_types=1);
namespace SwagBasicExample\Twig;
use Shopware\Core\Framework\Context;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class SwagCreateMd5Hash extends AbstractExtension
{
public function getFunctions()
{
return [
new TwigFunction('createMd5Hash', [$this, 'createMd5Hash']),
];
}
public function createMd5Hash(string $str)
{
return md5($str);
}
}
Of course, you can do anything else here that you can do with PHP. So, in theory, you could also retrieve data from the database or use other PHP logic.
The only thing missing now is the services.xml file. We need to register the function in the DI container.
<!-- <plugin root>/src/Resources/config/services.xml -->
<services>
<service id="SwagBasicExample\Twig\SwagCreateMd5Hash" public="true">
<tag name="twig.extension"/> <!--Required-->
</service>
</services>
Once that's done, you can use the Twig function in the theme.
{{ createMd5Hash('Hello World') }}
From the blog
Random posts from my blog.