Appsilon/shiny.i18n

Translate value in vector

Closed this issue · 2 comments

Thank you for development of this package. I am able to successfully use the package, but wonder if I can use the package to translate the values within a vector.

For instance, in the iris dataset, can I add to my JSON file to feed the translations for the values in the Species column?
{
"en": "setosa",
"pl": "setosa_pl",
"hr": "setosa_hr"
},
{
"en": "versicolor",
"pl": "versicolor_pl",
"hr": "versicolor_hr"
},
{
"en": "virginica",
"pl": "virginica_pl",
"hr": "virginica_hr"
}

This would allow the app user to view the name of the Species in their preferred language, if Species were to be plotted as an axis variable.
image

I can't find documentation of this using the i18n package.

Do you suggest using another package for this? Thanks again!

Hi @Spswitzer , thanks for using the package. So there're two things here. First of all, shiny.i18n supports translating vectors, see for example:

> i18n <- Translator$new(translation_json_path = "translation.json")
> i18n$set_translation_language("pl")
> i18n$t(c("Hello Shiny!", "Right", "Left"))
[1] "Witaj Shiny!" "Prawo"        "Lewo" 

But, the use-case you mentioned is a little trickier as this is a direct integration into the data. Let me suggest this workaround. Note that here I combined server-side translation and UI translation.

library(shiny)
library(shiny.i18n)
library(dplyr)

i18n <- Translator$new(translation_json_path = "translation.json")

ui <- fluidPage(
  usei18n(i18n),
  h1(i18n$t("Hello")),
  actionButton("change", i18n$t("Change language")),
  tableOutput("tab1")
)

server <- function(input, output, session) {

  i18n_r <- reactive({
    i18n
  })

  observeEvent(input$change, {
    lang <- ifelse(as.numeric(input$change) %% 2, "pl", "en")
    update_lang(session, lang)
    i18n_r()$set_translation_language(lang)
  })

  irisData <- reactive({
    levels(iris$Species) <- i18n_r()$t(levels(iris$Species))
    iris
  })

  output$tab1 <- renderTable({
    irisData()
  })
}

shinyApp(ui, server)

Bs8X5LPZ7z

LMK if there's anything unclear about this code.

Thank you for your quick response and your example. I will attempt to implement.

👍