You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shiny的prettyRadioButton选项标签中添加换行?

解决Shiny中prettyRadioButtons选项换行问题

方法1:启用HTML渲染选项内容

prettyRadioButtons默认会转义HTML标签,直接写<br>无效。可以通过choicesOpt参数开启HTML解析,让换行标签生效:

修改server中的renderUI部分,添加choicesOpt = list(html = TRUE):

output$example <- renderUI({
  tagList(
    prettyRadioButtons(inputId = "cf_method",
                       label = h4(strong("Method", style = "color:black")),
                       icon = icon("check"), animation = "jelly",
                       choices = choice_dic, 
                       selected = "1",
                       choicesOpt = list(html = TRUE) # 开启HTML解析
    )
  )
})

此时你定义的choice_dic里的<br>会被正确解析为换行。

方法2:用CSS强制自动换行(无需手动加<br>)

如果不想手动插入换行标签,可通过CSS让选项文本根据容器宽度自动换行。在ui中添加样式规则:

修改ui部分,在fluidPage内加入tags$style:

ui <- fluidPage(
  tags$style(
    # 针对sidebarPanel中的单选按钮选项设置自动换行
    ".sidebarPanel .pretty .state label {
      white-space: normal !important;
      line-height: 1.4;
    }"
  ),
  tabItem(tabName = "CF", br(),
          sidebarLayout(
            sidebarPanel(width = 3,
                         uiOutput("example")),
            mainPanel(width = 9,
                      fluidPage(width = NULL,
                                uiOutput("display"))
            )))
)

同时去掉choice_dic里的<br>,直接保留完整文本:

choice_dic <- c("Option 1 name (option 1 method name)" = "1",
                "Option 2 name (option 2 method name)" = "2")

文本会自动根据sidebarPanel的3列宽度换行,适配更灵活。

完整示例代码(方法2版本)

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  tags$style(
    ".sidebarPanel .pretty .state label {
      white-space: normal !important;
      line-height: 1.4;
    }"
  ),
  tabItem(tabName = "CF", br(),
          sidebarLayout(
            sidebarPanel(width = 3,
                         uiOutput("example")),
            mainPanel(width = 9,
                      fluidPage(width = NULL,
                                uiOutput("display"))
            )))
)

server <- function(input, output) {
  choice_dic <- c("Option 1 name (option 1 method name)" = "1",
                  "Option 2 name (option 2 method name)" = "2")
  output$example <- renderUI({
    tagList(
      prettyRadioButtons(inputId = "cf_method",
                         label = h4(strong("Method", style = "color:black")),
                         icon = icon("check"), animation = "jelly",
                         choices = choice_dic, selected = "1")
    )
  })

  observe({
    print(input$cf_method)
  })
}

shinyApp(ui = ui, server = server)

内容的提问来源于stack exchange,提问作者user375779

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 05:25:33