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 usingtrim()
, 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!