0

In Drupal 7, I can create a custom function in the template.php file. here is an example of custom function:

function myCustomFunction($arg) {
    $data_converted = $arg . 'XXXXX';
    return $data_converted;
}

...and in Drupal 7 and inside my template I can call this function with passing a specific data / field data.

In Drupal 8, it's different, and I don't see how to proceed. In my .theme file, I tried to create a custom function. In my twig template I tried to call this custom function but I get an error : function not found.

With drupal 8 how can I proceed to implement a custom function (with args) ? Thanks for your help, and eventualy yours examples.

2

In Drupal 7, I can create a custom function in the template.php file

To cut a very long story short, in Drupal 7 you should ideally have been calling that function in a preprocess function, to prepare variables for the template, rather than calling it from the template directly.

In Drupal 8 it's now Fine™ to call functions directly in the template. But now you can't use PHP directly, so you need to write a Twig extension.

It's very easy, core even has its own that you can copy from. The important thing is to register the service class with a twig.extension tag, so the system picks it up.

See this blog post for a full example.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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