如何在Shiny的prettyRadioButton选项标签中添加换行?
方法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
相关产品推荐
相关产品推荐

