Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig Variable Variables for a method

Tags:

php

twig

symfony

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!

like image 399
Matt Cavanagh Avatar asked Mar 26 '15 16:03

Matt Cavanagh


People also ask

How do you set a global variable in Twig?

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.


1 Answers

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' }}
like image 138
Matteo Avatar answered Nov 03 '22 02:11

Matteo