Search code examples
rshinykatex

Latex with katex rendered double in R Shiny app and as unwanted popup in new window


My R Shiny application uses Katex to render the latex - this is my header in my navbarPage() in my ui:

      header = tags$head(
        # use Katex to autorender all tex: https://katex.org/docs/autorender.html
        tags$link(rel="stylesheet",
                  href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css",
                  integrity="sha384-vKruj+a13U8yHIkAyGgK1J3ArTLzrFGBbBc0tDp4ad/EyewESeXE/Iv67Aj8gKZ0",
                  crossorigin="anonymous"),
        tags$script(defer="",
                    src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js",
                    integrity="sha384-PwRUT/YqbnEjkZO0zZxNqcxACrXe+j766U2amXcgMg5457rve2Y7I6ZJSm2A0mS4",
                    crossorigin="anonymous"),
        tags$script(defer="",
                    src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/auto-render.min.js",
                    integrity="sha384-+VBxd3r6XgURycqtZ117nYw44OOcIax56Z4dCRWbxyPt0Koah1uHoK0o4+/RRE05",
                    crossorigin="anonymous",
                    onload="renderMathInElement(document.body);"),

It works very well to render the latex quickly in my app. However, the individual latex expressions are also rendered a second time in new pop-up windows (or in the Viewer in R Studio if it's open), for example: App latex 2nd rendering in R Studio Viewer

I'm not sure why this behavior is happening - I've tried adjusting whether mathml or html is rendered from katex to ensure only one version is created, but I'm not sure which part of my Shiny app settings this behavior is driven by or where to look to start fixing it. Has anyone else had this issue and solved it?


Solution

  • I guess you are using the katex package. Then you have to set the option preview = FALSE. And you don't need to include the JavaScript files in the header.

    library(katex)
    library(shiny)
    
    shinyApp(
      ui = fluidPage(
        tags$head(
          tags$link(
            rel="stylesheet",
            href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css",
            integrity="sha384-vKruj+a13U8yHIkAyGgK1J3ArTLzrFGBbBc0tDp4ad/EyewESeXE/Iv67Aj8gKZ0",
            crossorigin="anonymous"
          )
        ),
        HTML(katex_html(
          "\\int f = \\pi", 
          displayMode = TRUE, 
          preview = FALSE, 
          output = "html")
        )
      ),
      
      server = function(input, output, session) { }
    )