Laurent
Laurent

Reputation: 349

Twig - Adding translation in a choice option

I am fighting with problem in customizing form in twig.

My problem is to add translation in option of a choice value, for example {{ 'years'|trans }}. I can set it in the FormType code by calling the translator but it's not that easy and it should be done in twig as it's the place for presentation. I can't have to make working the following :

{{ numberYears ~ ' ' ~ 'years'|trans ~ ' -' ~ cost * numberYears ~ 'credits'|trans }}

If someone can help, it would be with great pleasure!

[EDIT]

In fact my question is not well-formed, so I re-formulate it below:

In my FormType I have the following code, where I want to translate year, years and credits. I think I can do it in the FormType by calling the translator, but I think it's better to have the choices array as an associative array($cost, $year) and then build the label in twig based on key, value, but I can't find the block to override.

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $userCredits = 15;
    $cost = 5;

    $yearsMax = min(3, (int) floor($userCredits / $cost));
    $selectYears = array();
    for ($i = 1; $i <= $yearsMax; $i++) {
        $years = $i == 1 ? ' year' : ' years';
        $value = $i . $years . ' -' . $cost * $i . ' credits';
        $selectYears[$value] = $i;
    }
    $builder
        ->add('renewalYear', ChoiceType::class, array(
            'label' => 'text.renew_for',
            'required' => true,
            'choices'  => $selectYears
            ))
    ;
}

Upvotes: 3

Views: 1171

Answers (2)

Matteo
Matteo

Reputation: 39380

try surrounding with parenthesis:

{{ numberYears ~ ' ' ~ ('years'|trans) ~ ' -' ~ cost * numberYears ~ ('credits'|trans) }}

Hope this help

Upvotes: 0

xabbuh
xabbuh

Reputation: 5881

Since Symfony 2.7 you can use the choice_translation_domain option to translate choice values.

Upvotes: 1

Related Questions