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 https://gist.github.com/rgasch/5c7f76c0e953f6782478420bb4c1da57 for an example of how to do this.

2 Likes

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