How to pass function into Twig view?

If i have function global, example

function url($url){
       return base_path() . '/' . $url;

How can i using this function in Twig view?

{{ url('example') }}

It’s return unknown ‘url’ function.

You need to create a custom Twig extension in order to make this function known inside your templates. Please see for an example of how to do this.


You can do this with the addGlobal function on the Twig instance.

$view = $app->getContainer()['view'];
$view->getEnvironment()->addGlobal('url', function ($url) {
    return url($url);
1 Like