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

为什么R Shiny无法识别我添加的<br>换行命令?

问题排查与修复方案

问题原因

代码中paste0()函数会将htmltools::HTML()生成的HTML类型对象强制转换为普通字符串,Shiny遇到普通字符串时会默认转义其中的HTML标签,因此<br>会被当作普通文本展示,无法实现换行效果。

修复方案

当前场景下不需要使用paste0做字符串拼接,直接保留htmltools::HTML对象即可,修改long_text的赋值代码:

# 去掉外层的paste0即可
long_text <- htmltools::HTML("I have a lot of text. <br><br>And I want it on different lines.<br><br> This should work, but R is being....<br><br>difficult.")

如果后续确实需要拼接多个包含HTML标签的字符串,需要将htmltools::HTML包裹在paste0的外层,保证最终输出的是HTML对象而非普通字符串:

# 多字符串拼接的正确写法示例
long_text <- htmltools::HTML(paste0(
  "第一行文本<br><br>",
  "动态变量内容:", your_variable, "<br><br>",
  "第三行文本"
))

修改后完整可运行代码

library(shiny)

long_text <- htmltools::HTML("I have a lot of text. <br><br>And I want it on different lines.<br><br> This should work, but R is being....<br><br>difficult.")


ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      br(),
      actionButton(inputId = "text_info", 
                   label = "My R Sob Story", style = "color: #FFFFFF; background-color: #CA001B; border_color: #CA001B")
    ),
    mainPanel(
    )
  )
)

server <- function(input, output) {
  observeEvent(input$text_info, {
    showModal(modalDialog(long_text, title = strong("Why R you doing this to me?")))
  })
}

shinyApp(ui = ui, server = server)

内容的提问来源于stack exchange,提问作者J.Sabree

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:06:01