I tried the answers of this question , but it's not working. It's weird and I cannot reproduce the behavior:
obj2arr
casts the object to an array, to make it iterable. prepareForTwig
is just using trim()
, etc. - the string is outputted correctly. {% 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. substr()
to get rid of the *
(star + 1 space) , but didn't notice/expect the second space.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.