Currently I place my function in a class and pass an instance of this class into template and call my required function as a class method.
{{ unneededclass.blah() }}
I need to do like below
{{ blah() }}
Is it possible?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Update 5/14/2015
Commenters point out that I’m mostly wrong. If you really need a function, and not a filter or macro, you can do it as suggested in the Twig docs:
And use like
In short, no, this is not possible.
However, hope is not lost!
Filters
If this function
blah()of yours is meant to modify an existing variable, then it is a filter.An example:
(The first argument is the variable you are filtering, the second is supplied by normal means)
Macros
If, as you have indicated above, your function simply outputs HTML, then it is a good candidate for a macro.
An example:
Or with parameters:
Why?
The thing to remember is that Twig templates represent a view, in terms of MVC. This means they are isolated in terms of their environment, and can only represent the context you pass them via the data array you pass in the
$template->render()method.This is a good thing, as it decouples your presentation from your logic and data. If you can arbitrarily call functions, then you suddenly increase that coupling, which is a bad thing.
The other reason for this is the way PHP handles callbacks. Think about how you would have to pass that function into your template… Probably something like this:In your template, the context variableblahis now just a string containing'blah'.In vanilla PHP, when you use variable functions like this (try to use a string variable like a function), it (more or less) performs a lookup for that function, then calls it. You are not passing the function, just it’s name.The thing is, you cannot possibly pass a function into a template, because PHP’s only mechanism for doing this is by name-string, and once inside a template, that name is no longer a function name and just a string.A little bit long winded, but I hope that helps!
If you want more documentation, the official docs are here.