问题
在动态创建 ui-elements ( shiny.tag
, shiny.tag.list
, ...) 时,我经常发现很难将其与我的代码逻辑分开,并且通常会以嵌套tags$div(...)
、循环和条件语句的混杂而告终。虽然看起来很烦人而且很难看,但它也很容易出错,例如在更改 html 模板时。
可重现的例子
假设我有以下数据结构:
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")
)
)
)
如果我现在想将此结构推送到 ui-tags 中,我通常会得到如下结果:
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)
如您所见,与我的真实示例相比,这已经很混乱了。
所需的解决方案
我希望找到接近R模板引擎的东西,这将允许分别定义模板和数据:
# 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}}"
)
)
以前的尝试
首先,我认为这shiny::htmlTemplate()
可以提供一个解决方案,但这仅适用于文件和文本字符串,而不适用于shiny.tag
s。我还查看了一些 r-packages,比如whisker
,但它们似乎有相同的限制并且不支持标签或列表结构。
谢谢!