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

如何在Shiny应用中结合renderUI手动加载带cancel扩展的MathJax?

解决Shiny中renderUI无法渲染MathJax公式的问题

问题核心是:MathJax初始化时仅扫描页面现有内容,通过renderUI动态生成的内容属于后续加载,MathJax不会自动重新解析;而withMathJax()内部会自动触发MathJax的重新渲染逻辑,因此能正常工作。

针对你的场景,提供两种可行解决方式:

方式一:在renderUI中用withMathJax()包裹内容

直接在renderUI的返回值外层添加withMathJax(),动态内容生成后会自动触发MathJax解析,原有的cancel扩展配置依然生效。修改后的server代码如下:

server <- function(input, output, session) {
  output$main <- renderUI({
    withMathJax(out_text)
  })
}

方式二:手动触发MathJax重新排版

若不想依赖withMathJax(),可在动态内容加载完成后,手动调用MathJax的typeset()方法重新解析页面内容。修改后的server代码如下:

server <- function(input, output, session) {
  output$main <- renderUI({
    tagList(
      out_text,
      tags$script(HTML("MathJax.typeset();"))
    )
  })
}

完整可运行代码(以方式一为例)

library(shiny)

js <- "
window.MathJax = {
  loader: {load: ['[tex]/cancel']},
  tex: {packages: {'[+]': ['cancel']}}
};
"

out_text <- "Equation 1: $$1+1=2$$
Equation with cancel: $$\\cancel{1+1}=0$$"

ui <- fluidPage(
  tags$head(
    tags$script(async="", src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"),
    tags$script(HTML(js))
  ),
  uiOutput("main")
)

server <- function(input, output, session) {
  output$main <- renderUI({
    withMathJax(out_text)
  })
}

shinyApp(ui, server)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:37:45