Skip to content

Bug: No support for Template Jinja2 i18n (maybe I am wrong - Templates without i18n works) #4576

@ChameleonRed

Description

@ChameleonRed

Description

I read documentation and I found that I can use Templates - it works, but I try to use it with i18n.

Problem is that for all request language settings are same because is only one Jinja2 environment.

I can modify this environment per request with request.app.template_engine but what if I modify this and next parallel request modify it to - at the end Polish user can get Chinese translation since it is async.

Example of setup:

jinja_environment = Environment(
    loader=FileSystemLoader(
        searchpath=[
            'template',
            'authentication/template'
        ]
    ),
    extensions=[
        'jinja2.ext.i18n'
    ],
    autoescape=True,
)
# translations = get_translation(settings.locale_settings.possible_locales)
# jinja_environment.install_gettext_translations(translations)

listastar use request.app.engine to render do so if I do:

translations = get_translation(settings.locale_settings.possible_locales)
jinja_environment.install_gettext_translations('pl-PL')

No idea if request like this fail or not.

@get('/')
async def index(request: Request) -> Template:
    translations = get_translation(settings.locale_settings.possible_locales)
    # assume cookie read here
    jinja_environment.install_gettext_translations('pl-PL')
    return Template(
        template_name='index.jinja',
        media_type='text/html',
        context={
            'redirect_url': request.url.path,
        }
    )

since meanwhile can be 'en-US'

@get('/')
async def index(request: Request) -> Template:
    translations = get_translation(settings.locale_settings.possible_locales)
    # assume cookie read here
    jinja_environment.install_gettext_translations('en-US')
    return Template(
        template_name='index.jinja',
        media_type='text/html',
        context={
            'redirect_url': request.url.path,
        }
    )

Examples are simplified and handlers can be much longer.

URL to code causing the issue

No response

MCVE

Steps to reproduce

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Screenshots

No response

Logs


Litestar Version

latest 2.19

Platform

  • Linux
  • Mac
  • Windows
  • Other (Please specify in the description above)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Bug 🐛This is something that is not working as expected

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions