简体   繁体   中英

Twig: How to concat and translate strings?

I tried the answers of this question , but it's not working. It's weird and I cannot reproduce the behavior:

  • I cleared the cache
  • Concat works (it output's the right string)
  • The concated string as a variable is not translateable
  • The concated string pasted as a string is translateable
  • Edit : obj2arr casts the object to an array, to make it iterable. prepareForTwig is just using trim() , etc. - the string is outputted correctly.
  • Edit 2 : {% set transVar = (key|prepareForTwig) %} (without prefix) doesn't work as well.

yml:

# Resources/translations/messages.en.yml
my:
   keywords:
       keyword1: K1
       keyword2: K2
       # ...

twig:

{# my.twig.html #}
{% for key, value in data|obj2arr %}
    {% set transVar = 'my.keywords.' ~ (key|prepareForTwig)) %}

    {{ transVar }}<br/>                    {# output, e.g.: my.keywords.keyword1 #}
    {{ transVar|trans}}<br/>               {# output, e.g.: my.keywords.keyword1 #}  
    {{ 'my.keywords.keyword1'|trans }}     {# output: K1 #}
{% endfor %}

EDIT:

CustomTwigExtension.php

class CustomTwigExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('obj2arr', array($this, 'obj2arrFilter')),
            new \Twig_SimpleFilter('prepareForTwig', array($this, 'prepareForTwigFilter')),
        );
    }

    public function obj2arrFilter($obj)
    {
        return (array)$obj;
    }

    public function prepareForTwigFilter($str) {
        $str = trim($str);
        $str = strtolower($str);
        $str = substr($str, 2, strlen($str)); // obj2arr() prefixes "*"

        return $str;
    }

    public function getName()
    {
        return 'custom_twig_extension';
    }
}

Thanks in advance!

Others examples didn't seem to work in my case, this is what I ended up using:

{{ "my.prefix.#{ myVariable }.my.postfix" | trans }}

The translation string has to be between double quotes.

Every answer of outputting concated translationstrings was right, example:

{% 'my.prefix.' ~ extendByKeyword | trans }}

The problem was a weird generated space:

  • (array) $obj added * (there are two spaces after the star) as a prefix to the key -variable.
  • I used substr() to get rid of the * (star + 1 space) , but didn't notice/expect the second space.
  • After comparing the strings with strlen() , I found the cause.

Thanks to @Artamiel and @CarlosGranados for your help.

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