With the Shiny package and its fluidPage()
function, language switching is perfectly supported by the shiny.i18n library. With the bslib package for making Shiny dashboards more attractive and the associated functions page_navbar()
or page_sidebar()
, it doesn't work and causes an error. page_navbar()
or page_sidebar()
expect a panel or navigation container and can't handle the initial usei18n()
function. Is there a known workaround? What's the alternative procedure with the bslib package so that the shiny.i18n library can also be used for a multilingual application?
library(shiny.i18n)
library(shiny)
library(bslib)
i18n <- Translator$new(translation_json_path='translations/translation.json')
i18n$set_translation_language('en')
# UI ---------------------------------------------------------------------------
ui <- page_navbar(
shiny.i18n::usei18n(i18n)
# header = card_body(shiny.i18n::usei18n(i18n)), I found this workaround with a Google search, but it didn't work.
selectInput(
inputId='selected_language',
label=i18n$t('Change language'),
choices = i18n$get_languages(),
selected = i18n$get_key_translation()
),
# Title ----------------------------------------------------------------------
title = i18n$t("Fitness Market Comparison"),
nav_spacer(),
)
server <- function(input, output, session) {
observeEvent(input$selected_language, {
update_lang(input$selected_language, session)
})
}
I don't see an issue when using shiny.i18n together with bslib.
The one thing here to note is that if you want to avoid the Navigation containers expect a collection ... warning you in particular can make use of a nav_panel()
inside the page_navbar()
, compare the below example with yours. The other thing is the placement of the shiny.i18n::usei18n(i18n)
. There are some options. Below I put it into the title argument of the nav_panel()
, but you can also do it different.
library(shiny.i18n)
library(shiny)
library(bslib)
i18n <- Translator$new(translation_json_path='translations/translation.json')
i18n$set_translation_language('en')
ui <- page_navbar(
nav_panel(
title = span(usei18n(i18n), i18n$t('Hello Shiny!')),
selectInput(
inputId='selected_language',
label=i18n$t('Change language'),
choices = i18n$get_languages(),
selected = i18n$get_key_translation()
)
),
nav_spacer(),
)
server <- function(input, output, session) {
observeEvent(input$selected_language, {
update_lang(session = session, input$selected_language)
})
}
shinyApp(ui, server)
translation.json
{
"cultural_date_format": "%d-%m-%Y",
"languages": ["en", "pl"],
"translation": [
{"en": "Hello Shiny!", "pl": "Witaj Shiny!"},
{"en": "Change language", "pl": "Zmienić język"}
]
}