twig dynamic variable call

无人久伴 提交于 2021-02-05 05:29:11

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/31404720/twig-dynamic-variable-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!