How to pass symfony translated sentences to twig?

Member

by rollin , in category: PHP Frameworks , a year ago

How to pass symfony translated sentences to twig?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , a year ago

@rollin 

To pass Symfony translated sentences to Twig, follow these steps:

  1. Install the Translation component if you haven't already:
1
composer require symfony/translation


  1. Configure the Translation component in your config/packages/translation.yaml file:
1
2
3
4
5
6
7
framework:
    default_locale: en
    translator:
        paths:
            - '%kernel.project_dir%/translations'
        fallbacks:
            - en


  1. Create a translations file under translations directory. For example, create messages.en.yaml to store English translations:
1
hello: Hello


  1. In your Symfony controller, use the trans() function to translate sentences and pass them to Twig:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentTranslationTranslatorInterface;

class YourController
{
    public function index(TranslatorInterface $translator): Response
    {
        $translatedSentence = $translator->trans('hello');
        
        return $this->render('your_template.html.twig', [
            'translatedSentence' => $translatedSentence,
        ]);
    }
}


  1. In your Twig template (your_template.html.twig), output the translated sentence:
1
{{ translatedSentence }}


When the template is rendered, the translated sentence will be displayed based on the current locale configuration. You can add more translations to the messages.en.yaml file or create additional translation files for different languages.

Related Threads:

How to register twig filter into symfony?
How to override form_errors() from twig in symfony?
How to render a twig template in a Symfony controller?
How to create a new twig template in Symfony?
How to send securely a form through twig & symfony?
How to get user input with twig and symfony?