Internationalization | Django LiveView

Django LiveView automatically passes the current language to handlers:

from django.utils import translation

@liveview_handler("show_content")
def show_content(consumer, content):
    # Get language from WebSocket message
    lang = content.get("lang", "en")

    # Activate language for this context
    translation.activate(lang)

    try:
        html = render_to_string("content.html", {
            "title": _("Welcome"),
            "message": _("This content is in your language")
        })

        send(consumer, {
            "target": "#content",
            "html": html
        })
    finally:
        # Always deactivate to avoid side effects
        translation.deactivate()

The language is automatically detected from the <html> tag:

{% load static i18n %}
<!doctype html>{% get_current_language as CURRENT_LANGUAGE %}
<html lang="{{ CURRENT_LANGUAGE }}">