I would like to be able to use some custom PHP code that generates an SVG image in my .tpl.twig file. Since I can't write PHP in a twig template I figured I should try and make a twig extension (http://symfony.com/doc/current/cookbook/templating/twig_extension.html)

How could this be done in Drupal? Or is there another way?


1 Answer 1


When you are using tfd7 you can use extensions, functions, etc. The easiest way to go is to create an own module for handling all the php-functions.

In your OWN_MODULE.module:

function OWN_MODULE_twig_function() {
  $functions = [];
  $functions['XYZ_unset_key'] = new TwigSimpleFunction('XYZ_unset_key', 'XYZ_unset_key_callable');


  return $functions;

function XYZ_unset_key_callable($key, $array) {
  return $array;

After that you can use the function XYZ_unset_key in your twig-files:

  {{ XYZ_unset_key('field_xyz', 'content') }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.