Prism.js runs as soon as its loaded, so any code blocks dynamically added afterward won't get highlighted. One option would be to load prism.js
dynamically in the server function as well.
output$sql <- renderUI({
tagList(
tags$script(src = "prism.js"),
HTML(txt)
)
})
But this is not very robust. You could easily load multiple copies of the script. And if you make it a shiny::singleton
or use htmltools::htmlDependency
to only load the script once, you could easily find yourself back in the original situation.
A better solution - Prism provides an API that lets you programmatically highlight code blocks: http://prismjs.com/extending.html#api
How about running Prism.highlightAll()
after rendering any code block?
library(shiny)
prismCodeBlock <- function(code) {
tagList(
HTML(code),
tags$script("Prism.highlightAll()")
)
}
prismDependencies <- tags$head(
tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/prism/1.8.4/prism.min.js"),
tags$link(rel = "stylesheet", type = "text/css",
href = "https://cdnjs.cloudflare.com/ajax/libs/prism/1.8.4/themes/prism.min.css")
)
prismSqlDependency <- tags$head(
tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/prism/1.8.4/components/prism-sql.min.js")
)
ui <- fluidPage(
prismDependencies,
prismSqlDependency,
HTML("<pre><code class='language-sql'>SELECT * FROM mytable WHERE 1=2
-- this chunk should be syntax highlighted and it is
</code></pre>"),
HTML("<pre>SELECT * FROM mytable WHERE 1=2
-- this chunk should not be syntax highlighted
</code></pre>"),
htmlOutput("sql")
)
server <- function(input, output) {
txt <- "<pre><code class='language-sql'>SELECT * FROM mytable WHERE 1=2
-- this chunk should be syntax highlighted but isn't for some reason,
-- presumably connected to it getting to the UI via renderText and htmlOutput
</code></pre>"
output$sql <- renderUI({
prismCodeBlock(txt)
})
}
shinyApp(ui, server)
For further improvement, you could use Prism.highlightElement()
to be more efficient. Could also create an HTML widget out of these Prism code blocks to abstract away the messy details.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…