How to translate concatenated string in twig template using Symfony2 translator

这一生的挚爱 提交于 2019-12-10 12:37:12

问题


I have a translation yml file like this:

tag:
  myfirsttag: Tag number one
  secondtag: Tag number two
  ....

and twig template like

    <select name="tag" required="required">
        {% for tag in tag_list %}
            <option value="{{ tag }}">{{ "tag." ~ tag | trans(domain='mydomain') }}</option>
        {% endfor %}
    </select>

So here is the problem. Items in select are rendered like "tag.myfirsttag", not translated. If I replace "tag." ~ tag with hardcoded string like "tag.myfirsttag" it works well. So obviously it is related to concatenation but official docs doesn't say anything about it.

To be more clear and simple

I can translate

{{ "hello.world" | trans(domain='mydomain') }}

but can't translate

{{ "hello." ~ "world" | trans(domain='mydomain') }}

回答1:


The solution is to put the string into parentheses as described here:

works:

{{ 'hello.world' | trans }}

doesn't work:

{{ 'hello.' ~ 'world' | trans }}

works:

{{ ('hello.' ~ 'world') | trans }}



回答2:


to translate contact strings you have to make this thing:

{{ ("some string " ~ entity.type ~ " another string")|trans }}

But try writing string to translate like params: eg:

some.funny.string




回答3:


Is it an associative array, right? Then you should be looping over key=>value pair

<select name="tag" required="required">
    {% for key,tag in tag_list %}
      <option value="{{ key }}">{{ tag | trans(domain='mydomain') }}</option>
    {% endfor %}
</select>

Or is your array deeper:

<select name="tag" required="required">
    {% for tag in tag_list %}
      {% for key,value in tag %}
        <option value="{{ key }}">{{ value | trans(domain='mydomain') }}</option>
      {% endfor %}
    {% endfor %}
</select>


来源:https://stackoverflow.com/questions/22984545/how-to-translate-concatenated-string-in-twig-template-using-symfony2-translator

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