This questions is related to this one.
EDIT
I reformulated the question to reproduce the problem in more complex app.
I'm trying to include math mode in tables. Solution of @Stéphane Laurent using katex in EDIT 2 works excellent. I edited the code as my app includes a lot of tables which have names including string coef_
.
library(shiny)
js <- "
$(document).on('shiny:value', function(event) {
if(event.name.indexOf(event.name.match(/\\b\\w*coef_\\w+\\b/g)) > -1){
if(event.value.match(/(%%+[^%]+%%)/g) !== null) {
var matches = event.value.match(/(%%+[^%]+%%)/g);
var newvalue = event.value;
for(var i=0; i<matches.length; i++){
var code = '\\\\' + matches[i].slice(2,-2);
newvalue = newvalue.replace(matches[i], katex.renderToString(code));
}
event.value = newvalue;
} else {
event.value;
}
}
});
"
In case that table name does not include string coef_
or n case that table with name including string coef_
does not include terms with %%
, js
should have no impact on it.
# UI 1
fluidPage(
tags$head(
tags$link(rel="stylesheet", href="https://cdn.jsdelivr.net/npm/katex@0.10.0-beta/dist/katex.min.css", integrity="sha384-9tPv11A+glH/on/wEu99NVwDPwkMQESOocs/ZGXPoIiLE8MU/qkqUcZ3zzL+6DuH", crossorigin="anonymous"),
tags$script(src="https://cdn.jsdelivr.net/npm/katex@0.10.0-beta/dist/katex.min.js", integrity="sha384-U8Vrjwb8fuHMt6ewaCy8uqeUXv4oitYACKdB0VziCerzt011iQ/0TqlSlv8MReCm", crossorigin="anonymous"),
tags$script(HTML(js))
),
titlePanel("Hello Shiny!"),
mainPanel(
numericInput("mean", "Enter mean", value = 1),
tableOutput("coef_table1"),
tableOutput("coef_table2"),
tableOutput("table")
))
# SERVER
server <- function(input, output) {
output$table <- renderTable({
x <- rnorm(2)
y <- rnorm(2, input$mean)
tab <- data.frame(x = x, y = y, z = c("hello", "%%gamma%%%%delta%%"))
rownames(tab) <- c("%%alpha%%", "%%beta%%")
tab
}, rownames = TRUE)
}
However, when I create js file with code in js
variable, save it in www
folder and load it, it does not work:
# UI 2
fluidPage(
tags$head(
tags$link(rel="stylesheet", href="https://cdn.jsdelivr.net/npm/katex@0.10.0-beta/dist/katex.min.css", integrity="sha384-9tPv11A+glH/on/wEu99NVwDPwkMQESOocs/ZGXPoIiLE8MU/qkqUcZ3zzL+6DuH", crossorigin="anonymous"),
tags$script(src="https://cdn.jsdelivr.net/npm/katex@0.10.0-beta/dist/katex.min.js", integrity="sha384-U8Vrjwb8fuHMt6ewaCy8uqeUXv4oitYACKdB0VziCerzt011iQ/0TqlSlv8MReCm", crossorigin="anonymous"),
tags$script(src="math_in_tables.js")
),
titlePanel("Hello Shiny!"),
mainPanel(
numericInput("mean", "Enter mean", value = 1),
tableOutput("coef_table1"),
tableOutput("coef_table2"),
tableOutput("table")
))
Math mode no longer works in the first table. What am I missing here? There are no errors in browser.