Search code examples
rshinyknitrr-markdownmathjax

How to include html code with reactive MathJax elements in Shiny?


I am working on a shiny app that is intended to help students. It generates solution for each student with some equations using student specific input values.

The problem is that the MathJax equations are rendered as regular text, see the minimal example and this image:

enter image description here

Any idea how dynamic MathJax elements could be rendered properly?

My current approach:

  • use an rmarkdown document (solu_template.Rmd) with input parameter (params$student) to create student specific markdown file;
  • render the markdown file and include it in the ui.

Reactive, dynamically changing MathJax elements are feasible as this example shows. However, I would like to use more complex files and keep the convenience of preparing the solution template as an rmarkdown file.

Additional attempts:

  • direct use of the html file generated by render(), but I do not know how to include it in the ui as a dynamically changing component;
  • read the generated html file with readLines() and use htmlOutput to display it; no success, just a pile of code.

So, using this approach the question is how to render/display a dynamically changing html file?

All ideas, suggestions are welcome!

app.R

library(shiny)
library(markdown)

shinyApp( 

  ui = fluidPage(
    selectInput("student", "Student:", 
      choices = c("Student1", "Student2", "Student3")),
    actionButton("show_solu", "Run!"),

    hr(),
    withMathJax(),
    htmlOutput("solu")
  ),

  server = function(input, output, session) {
    output$solu <- eventReactive(input$show_solu, {
      rmarkdown::render("solu_template.Rmd",
        quiet = F, clean = F,
        params = list(student = input$student))

      solu <- renderMarkdown("solu_template.knit.md")
    }
    )
  }
)

solu_template.Rmd

---
title: "Solution"
params:
  student: Student1
output:
  html_document:
    theme: readable
---

```{r, echo = FALSE}
S = list(Student1 = 1, Student2 = 2, Student3 = 3)
s = S[[params$student]]
```
## Heading

Student dependent initial value:
$s = `r s`$

Some nice reasoning which yields to this equation:

$R = s^2 + \sqrt{2} = `r signif(s^2 + sqrt(2), 3)`$

Solution

  • Here is the solution with the renderMarkdown() approach:

    The following line should be added to the html code generated by renderMarkdown(), this way the browser will know that the output should be rendered considering MathJax elements:

    "<script>MathJax.Hub.Queue(["Typeset", MathJax.Hub]);</script>"
    

    Regarding the above example, this should be added to the end of the server function of app.R:

    solu = paste(solu, "<script>MathJax.Hub.Queue([\"Typeset\", MathJax.Hub]);</script>")