Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

twig dynamic variable call

I passed data in 3 languages to the twig template and display this data in this way:

{% set lang=app.request.get("lang")%}
{% for item in contests%}
    {% if lang=="fa"%}
        {{item.titlefa}}
    {% elseif lang=="en"%}
        {{item.titleen}}
    {% elseif lang=="ar"%}
        {{item.titlear}}
    {% endif%}
{% endfor%}

It is wirking but I must create 3 if condition for each object in "contests" How can i show data in this logic:

{% set lang=app.request.get("lang")%}
 {{item.title~lang}}
{% endfor%}

that can call proper method in contest

like image 823
M Gholami Avatar asked Jan 08 '23 23:01

M Gholami


1 Answers

You can use the attribute TWIG function for call at runtime a method name, as example:

    {% set lang=app.request.get("lang")%}
    {% methodname = 'title'~lang %}
      {% for item in contests%}
        {{ attribute(item, methodname) }}
      {% endfor%}

Hope this help

like image 200
Matteo Avatar answered Jan 10 '23 20:01

Matteo