How to Call Static Function with parameters In Twig Template 3.0

How to call my static function with parameters in the twig template 3.0 without going through the controller?

For exemple:

{{ Helper::url('/link') }}

My Static Class:

public static function url(string url) {
 $host = $_SERVER['HTTP_HOST'] == 'localhost' ? URL_TEST : URL_BASE;

if (str_starts_with($url, '/')):
    return $host . $url;
return $host . '/' . $url;


Looks from the documentation that it would be {% Helper::url('/link') %} ?

it doesn’t work like that

Well, logically you’d put the call in the controller, and just pass the static template variable to the template. Is there a particular reason you don’t?

You can’t call PHP functions/classes from Twig directly, you’d need to define them in Twig first.

$twig = new Environment(...);
  new TwigFunction('url', function (string $url) { return Helper::url($url); })

And then in your template you can do:

{{ url('/link') }}

(url here is the first parameter passed to the TwigFunction class)

PS If you’re on PHP 7.4 or higher you can replace this

function (string $url) { return Helper::url($url); }

with this

fn (string $url) => Helper::url($url)

Same thing, different syntax.


Why doesn’t it work like this in the template as I said the twig template is diferent

Thank you very much, it worked perfectly well

1 Like