ceo40
February 18, 2021, 9:59pm
1
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;
endif;
return $host . '/' . $url;
}
}
Looks from the documentation that it would be {% Helper::url('/link') %}
?
ceo40
February 18, 2021, 11:03pm
3
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?
1 Like
rpkamp
February 19, 2021, 8:52am
5
You can’t call PHP functions/classes from Twig directly, you’d need to define them in Twig first.
$twig = new Environment(...);
$twig->addFunction(
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.
2 Likes
ceo40
February 20, 2021, 7:56am
6
Why doesn’t it work like this in the template as I said the twig template is diferent
ceo40
February 20, 2021, 8:03am
7
Thank you very much, it worked perfectly well
1 Like
system
Closed
May 22, 2021, 3:04pm
8
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.