Search code examples
imagesymfonytwigtranslationtranslate

How do you translate an image with Symfony and Twig


i am using Symfony for translate my Twig-templates. Everything is working fine but i need to set other images when a user change the language. How do i do that with Symfony and Twig?

Thank you


Solution

  • You can access locale variable from Twig using app.request.getLocale() and use it like:

    # template
    {% locale = app.request.getLocale(); %}
    {% image '@AppBundle/Resources/public/images/' ~ locale ~ '/example.jpg' %}
        <img src="{{ asset_url }}" alt="Example" />
    {% endimage %}
    

    Or you can try storing path to your images like regular translation resources:

    # messages.en.yml
    image.example: @AppBundle/Resources/public/images/en/example.jpg
    
    # template
    {% image 'image.example'|trans %}
        <img src="{{ asset_url }}" alt="Example" />
    {% endimage %}