Facilitating support for language localization in Panel

Using Streamlit I was able to make use of the format_func option in widgets in order to write an app in English but support multiple languages. Is there an equivalent or workaround to facilitate this same type of functionality in Panel? Here is the Streamlit code I was using for a selectbox widget:

example = st.selectbox(
                    translate_text("Mode:", language),
                    ("For", "Against"),
                    format_func=lambda x: translate_text(x, language),
                    key="test_key",
                )

Thanks for any feedback!

One way to do this is to set the name and options of the Select to a reference:

import panel as pn

pn.extension()

LANGUAGES = ["en-US", "fr-FR", "de-DE", "es-ES"]

OPTIONS = ["For", "Against"]

TRANSLATIONS = {
    "Mode:": {"en-US": "Mode:", "fr-FR": "Mode :", "de-DE": "Modus:", "es-ES": "Modo:"},
    "For": {"en-US": "For", "fr-FR": "Pour", "de-DE": "FĂĽr", "es-ES": "Para"},
    "Against": {"en-US": "Against", "fr-FR": "Contre", "de-DE": "Gegen", "es-ES": "Contra"},
}


def translate(text, language):
    if isinstance(text, list):
        return [translate(t, language) for t in text]
    return TRANSLATIONS.get(text, {}).get(language, text)


language = pn.widgets.Select(name="Language", options=LANGUAGES)


def get_options(language, options):
    return {translate(option, language): option for option in options}


mode = pn.widgets.Select(
    name=pn.bind(translate, text="Mode:", language=language),
    options=pn.bind(get_options, language=language, options=OPTIONS),
)

pn.Column(language, mode, mode.param.value).servable()

That’s really helpful, thanks! Now what if I already have a watch set up on that widget like this:

self.graph_type.param.watch(self.create_sidebar_widgets, "value")

The objective would be to utilize only English terms in the code itself but display Spanish to the customer. When they then picked “Contra” (for against) it would be reverse translated to “Against” so that it could be processed using English in the code. That’s sort of how it works using that Streamlit example. Giving the appearance that the app is in Spanish when, in fact, it’s all in English under the hood. Thanks!

1 Like

Its not fully clear to me if the Panel example above solves your problem or if you would like it to work a bit differently?

Yes I think I can work with and expand upon that as a good bit of starter code. Thanks Marc! Your solution was really helpful.