2

I am trying to create a theme for Drupal 7 with Twig. If I wanted to register a new PHP function, I should implement "hook_twig_function()" as the module explains.

My simple question is: where should I implement my functions? If I write code - as usual - inside my "template.php", I have this alert: "Unknown "my_module_coolfunction" function in "sites/all/themes/abc/templates/page.tpl.twig"

If I edited the "Extension.php" file, after every update, I would lost all my custom functions.

0

In the docs it says:

Functions

To register a new filter you should implement hook_twig_function() and return an indexed array with unique keys and new Twig_SimpleFunction as value.

function my_module_twig_function(){

To answer your question:

My simple question is: where should I implement my functions?

Notice how it uses "my_module", so clearly in your custom module .module file is where these function(s) should be added. If you don't have a custom module yet, then you will need to create one.

So if your custom module is named Hello Kitty, then in hello_kitty.module

function hello_kitty_twig_function(){
    $functions = [];
    $functions['coolfunction'] = new Twig_SimpleFunction('coolfunction','hello_kitty_coolfunction');
    return $filters;
}

function hello_kitty_coolfunction($param_1,$param_2...){
    // do what you need to do, and return something.
}

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.