提问人:ahnungslos 提问时间:11/9/2023 最后编辑:ahnungslos 更新时间:11/10/2023 访问量:62
如何基于嵌套列表创建嵌套的 div 元素
How to create nested div elements based on a nested list
问:
我想根据嵌套列表的元素递归创建闪亮的元素:div
text
nodes <- list(
list(
text = "RootA",
state = list(loaded = TRUE, opened = TRUE, selected = FALSE, disabled = FALSE),
children = list(
list(
text = "ChildA1",
state = list(loaded = TRUE, opened = TRUE, selected = FALSE, disabled = FALSE)
),
list(
text = "ChildA2",
state = list(loaded = TRUE, opened = TRUE, selected = FALSE, disabled = FALSE)
)
)
),
list(
text = "RootB",
state = list(loaded = TRUE, opened = TRUE, selected = FALSE, disabled = FALSE),
children = list(
list(
text = "ChildB1",
state = list(loaded = TRUE, opened = TRUE, selected = FALSE, disabled = FALSE),
children = list(
list(
text = "ChildB1a",
state = list(loaded = TRUE, opened = TRUE, selected = FALSE, disabled = FALSE)
),
list(
text = "ChildB1b",
state = list(loaded = TRUE, opened = TRUE, selected = FALSE, disabled = FALSE)
)
)
),
list(
text = "ChildB2",
state = list(loaded = TRUE, opened = TRUE, selected = FALSE, disabled = FALSE)
)
)
)
)
我尝试使用 ,但它只在顶层起作用:purrr:map
purrr::map(nodes, function(x){
if("text" %in% names(x)){
div(x$text)
}
})
这是我的预期输出(使用 style 参数仅用于说明):
library(shiny)
divs <- list(
div("RootA",
div("ChildA1"),
div("ChildA2"),
style = "background-color: aqua;"
),
div("RootB",
div("ChildB1",
div("ChildB1a"),
div("ChildB1b")),
div("ChildB2"),
style = "background-color: lightgreen;"
)
)
ui <- fluidPage(
divs
)
server <- function(input, output, session) {
}
shinyApp(ui, server)
答:
4赞
MrFlick
11/10/2023
#1
你需要做一些递归。这应该有效
to_div <- function(x) {
shiny::div(x$text, if ("children" %in% names(x)) lapply(x$children, to_div))
}
divs <- lapply(nodes, to_div)
这将返回
[[1]]
<div>
RootA
<div>ChildA1</div>
<div>ChildA2</div>
</div>
[[2]]
<div>
RootB
<div>
ChildB1
<div>ChildB1a</div>
<div>ChildB1b</div>
</div>
<div>ChildB2</div>
</div>
评论