Problem
When dynamically creating ui-elements (shiny.tag
, shiny.tag.list
, ...), I often find it difficult to separate it from my code logic and usually end up with a convoluted mess of nested tags$div(...)
, mixed with loops and conditional statements. While annoying and ugly to look at, it's also error-prone, e.g. when making changes to html-templates.
Reproducible example
Let's say I have the following data-structure:
my_data <- list(
container_a = list(
color = "orange",
height = 100,
content = list(
vec_a = c(type = "p", value = "impeach"),
vec_b = c(type = "h1", value = "orange")
)
),
container_b = list(
color = "yellow",
height = 50,
content = list(
vec_a = c(type = "p", value = "tool")
)
)
)
If I now want to push this structure into ui-tags, I usually end up with something like:
library(shiny)
my_ui <- tagList(
tags$div(
style = "height: 400px; background-color: lightblue;",
lapply(my_data, function(x){
tags$div(
style = paste0("height: ", x$height, "px; background-color: ", x$color, ";"),
lapply(x$content, function(y){
if (y[["type"]] == "h1") {
tags$h1(y[["value"]])
} else if (y[["type"]] == "p") {
tags$p(y[["value"]])
}
})
)
})
)
)
server <- function(input, output) {}
shinyApp(my_ui, server)
As you can see, this already is quite messy and still nothing compared to my real like examples.
Desired solution
I was hoping to find something close to a templating engine for R, that would allow to define templates and data separately:
# syntax, borrowed from handlebars.js
my_template <- tagList(
tags$div(
style = "height: 400px; background-color: lightblue;",
"{{#each my_data}}",
tags$div(
style = "height: {{this.height}}px; background-color: {{this.color}};",
"{{#each this.content}}",
"{{#if this.content.type.h1}}",
tags$h1("this.content.type.h1.value"),
"{{else}}",
tags$p(("this.content.type.p.value")),
"{{/if}}",
"{{/each}}"
),
"{{/each}}"
)
)
Previous attempts
First, I thought that shiny::htmlTemplate()
could offer a solution, but this would only work with files and text strings, not shiny.tag
s. I also had a look at some r-packages like whisker
, but those seems to have the same limitation and do not support tags or list-structures.
Thank you!
www
folder and then apply the style sheets? – LashleyhtmlTemplate()
would allow for conditionals and loops ala handlebars, mustache, twig... – Hexachlorophene