I'm attempting to do something that was very easy in PHP, but not so easy in twig.
Basically, I need to call a class method, but I need to be able to define the method to call via a string.
I have 3 methods: getControlvs
, getControlnc
and getControltr
. However, in order to call these methods, I need a seperate variable which determines which one to call.
This is what I'm attempting to call right now:
{% set neutPer = key.getControl~neutFaction %}
Where neutFaction
can be either "vs", "nc", or "tr".
This only seems to fire key.getControl and then that's it, the concatenation is lost.
Any ideas?
Thanks in advance!
If you are using Twig in another project, you can set your globals directly in the environment: $twig = new Twig_Environment($loader); $twig->addGlobal('myStuff', $someVariable); And then use {{ myStuff }} anywhere in your application.
You can use the attribute twig function:
First concatenate the string as:
{% set method = "getControl" ~ neutFaction %}
Then call as
{{ attribute(key, method) }}
You can pass arguments also as:
{{ attribute(key, method, arguments) }}
In addition, the defined test can check for the existence of a dynamic attribute:
{{ attribute(object, method) is defined ? 'Method exists' : 'Method does not exist' }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With