简体   繁体   中英

Concatenate suffix to a twig method

I have a method in class , which the last two characters returns a value or another. The methods are:

getLastnameAD, getLastnameIN getLastanemBB

I want to use a macro to pass two characters to get the value, more or less as follows.

{% macro getLastName (obj, suff) %}
    <span>Lastname: {{ obj.getLastname ~ suff }}</span>
{% endmacro %}

But I get the following error;

Method "getLastname" for object ... does not exist in ...

Do you know if do this is possible ? If it is not possible. Is there any solution ?

I can not edit the object and the method that generate it, so, i have to get it in the view because it is the only place where I can handle data.

Greetings and thank you.

The error that you showed is because Twig is trying to execute the getLastname() method in your object and it's not defined.

The solution is the one provided by @qooplmao in a previous comment and use the attribute() function :

{{ attribute(obj, 'getLastname' ~ suff) }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM