How to Make Your R Shiny App More Internationalized

Language Switching Usage Documentation

Preface

After mentioning the applicability of language switching to my senior fellow student at a meeting last time, I wrote a usage document this week, thinking, hey, this document can also be updated to the blog, so I'm updating it...

The use of shiny.i18n is actually best done synchronously from the very beginning of project creation, as this will be friendlier for repetitive text translation work. If you wait until all the code is written before adding language switching, then locating the translation texts one by one is a very energy-consuming task...

Installation and Loading

install.packages("shiny.i18n")
library(shiny.i18n)

Reference documentation: https://appsilon.github.io/shiny.i18n/index.html

Specific Operation Steps

1. Translation Text Preparation

Create a json file named "translations.json" in the root directory as shown in the figure. The content of this file is all the translation texts.

image-20250517225426447

2. JSON Side

Open with a code editor (such as VS code)

The translation file code format is as follows:

{
    "languages": ["key", "en", "cn", "jp"],         //Please do not modify key, otherwise it will report an error; the other language code ids don't matter
    "translation": [
      {
        "key": "app_title",
        "en":  "Sample Size Calculation Tool",
        "cn":  "样本量计算工具",
        "jp":  "サンプルサイズ計算ツール"
      },
      {
        "key": "btn_calc",
        "en":  "Calculate Sample Size",
        "cn":  "计算样本量",
        "jp":  "サンプルサイズ計算"
      },
      {
        "key": "lang_en",  "en": "English",   "cn": "英文", "jp": "英語"
      },
      {
        "key": "lang_cn",  "en": "Chinese",   "cn": "中文", "jp": "中国語"
      },
      {
        "key": "lang_jp",  "en": "Japanese",  "cn": "日语", "jp": "日本語"
      },
      {
        "key": "tab_home",
        "en" : "Home",
        "cn" : "首页",
        "jp" : "ホーム"
      },
      {
        "key": "tab_guidance",
        "en" : "Guidance",
        "cn" : "向导",
        "jp" : "ガイダンス"
      }
        
      //And so on, just fill in all the translation texts. This part of the work can be handed to AI to do more quickly and easily
        
        
        
            ]
  }

Here "key" represents the id, and "en", "cn", "jp" are the different language texts.

3. Global Settings (i.e., needs to apply to both UI and Server)

Add the following code before the app code:

i18n <- Translator$new(translation_json_path = "translations.json")
i18n$set_translation_language("en")

Load the translation texts and determine the default language.

4. Configure One or More Language Switchers

Here it shows how to set things up synchronously when there are multiple selectors. If only a single selector is needed, it doesn't need to be this complicated; just one-way tracking with observeEvent is enough.

#UI
##Here what is configured is a dropdown language selection box in the upper right corner; we call it lang_top
tags$div(
    id    = "lang_switcher_fixed",
    style = "position: fixed; top: 10px; right: 20px; width: 130px; z-index: 3000;",
    selectInput(
      inputId  = "lang_top",
      label    = NULL,                  
      choices  = c("中文" = "cn",
                   "English" = "en",
                   "日本語" = "jp"),
      selected = "en",                   # Give a default value first; the server will synchronize it later
      width    = "100%"
    )
  )

#Suppose there are other selection boxes or buttons elsewhere corresponding to lang_en->en; lang_cn->cn; lang_jp->jp

5. Replace All Label Texts with i18n$t()

Replace all label languages with the key corresponding to the json file, that is, i18n$t().

Example 1

Old:

#This is a long text
tags$p("Usage: Fill in values like alpha, power, effect size or standard deviation, and choose alternative hypothesis. Click 'Calculate Sample Size'. Power curves will be displayed.")

New:

tags$p(i18n$t("Usage"))

Here "Usage" is the "key" corresponding to each piece of translation text in the json file.

If the text is inside a function or in server code, this method can also be used for replacement, but some functions don't support it very well; you'll have to figure that out yourself.

Example 2
output$sidebar_instructions <- renderUI({ 
    req(input$myInnerTabs) 
    
    if (input$myInnerTabs == "Home") {
      tagList(
        h4(i18n$t("sidebar_home_h4")),
        tags$p(i18n$t("sidebar_home_p1")),
        tags$p(i18n$t("sidebar_home_p2")),
          ···
          #Omitted below

6. Server Side (Multiple Selection Box Synchronization)

If multiple selection boxes are not needed, then just directly update the corresponding i18n$set_translation_language.

#server

# Determine the current language (that is, the default language). This is also a unified outlet so that different selection boxes can synchronize
  lang_r <- reactiveVal("en")


# When buttons elsewhere are clicked → change reactiveVal
  observeEvent(input$lang_en, {
    lang_r("en")
  })
  observeEvent(input$lang_cn, { lang_r("cn") })
  observeEvent(input$lang_jp, { lang_r("jp") })

# When lang_top changes → change reactiveVal (req() can be used as double insurance)
  observeEvent(input$lang_top, {
    req(input$lang_top)
    lang_r(input$lang_top)
  }, ignoreInit = TRUE)

# Unified outlet: as long as lang_r() changes → update i18n, front-end text, and the remaining selection controls
  observeEvent(lang_r(), {
    cur <- lang_r()
    i18n$set_translation_language(cur)
    update_lang(cur, session) # Instantly switch all i18n$t()
    updateSelectInput(session, "lang_top", selected = cur)
  })#Here it synchronizes the selected item of the dropdown box lang_top; if there are others, they can also continue to be added

Done

After completing the above steps, language switching can be done quickly. Although this is quite a bit more troublesome than web page machine translation, the translation effect is guaranteed, and because local resources are loaded, the response is also extremely fast.

Improvement

Actually there should be a more convenient method, but currently this is the only method I have figured out that shiny can support. I feel this is a problem that can be solved efficiently with a script. I still need to learn a lot...

I have also seen multilingual switching functionality in quite a few blogs, all using i18n, but I don't know exactly how to do it on a blog: is it automatically translating after I finish writing an article and loading it locally, or do two texts need to be provided and preloaded... I feel the latter is a bit too troublesome for blog updates, but the language-switching translations on many blogs look especially exquisite and don't seem like machine translation, so I think that's really impressive.

4 comments

Leave a comment

Your email will not be published. Fields marked * are required.

☺ Emoticons
颜文字
阿鲁
推特

Replies inherit the original privacy. Keep this browser’s cookies; an email address alone cannot restore access.

  1. 辰耀
    WeChat / Android

    博主加油喔ヾ(≧∇≦*)ゝ

  2. Edge / Windows

    哟嘿,沙发!

    1. DavidYR Author

      沙发认证! ::aru:thumb::

Find an article