编辑Shiny.tag元素

时间:2018-07-31 11:02:11

标签: r shiny

背景

我想更改shinydashboard::box的某些元素。说,我想更改用于折叠box(collapsible = TRUE)的图标。查看输出,我需要做的就是相应地更改<i>标签:

(b <- box(collapsible = T))
# <div class="col-sm-6">
#   <div class="box">
#    <div class="box-header">
#       <div class="box-tools pull-right">
#         <button class="btn btn-box-tool" data-widget="collapse">
#           <i class="fa fa-minus"></i> ## change to <i class="fa fa-times">
#         </button>
#       </div>
#    </div>
#    <div class="box-body"></div>
#   </div>
# </div>

挑战

虽然我可以在b$children中进行一些递归循环,以找到正确的子元素,如

b$children[[1]]$children[[1]]$children[[2]]$children[[1]]$children[[1]]$attribs$class <- "fa fa-times"

我想知道,是否有没有更简单的方法?理想情况是类似于jQuery的语法吗?

另一种选择是编写自己的box函数,但是我想避免代码重复。

2 个答案:

答案 0 :(得分:1)

您可以编写一个辅助函数来编辑生​​成的HTML。我们可以使用xml2中的函数来解析和编辑html。例如

swap_node <- function(x, xpath, newval) {
  parsed <- xml2::read_html(as.character(x))  
  oldnode <- xml2::xml_find_all(parsed, xpath)
  newnode <- xml2::read_html(as.character(newval))
  xml2::xml_replace(oldnode, newnode)
  shiny::HTML(as.character(xml2::xml_find_first(parsed, "//body/*")))
}

然后您可以像使用它

b <- shinydashboard::box(collapsible = T)
swap_node(b, "//i", shiny::tags$i(class="fa fa-times"))

但这在字符串而不是对象的世界中起作用。

答案 1 :(得分:1)

这是一个在搜索具有给定属性的给定类型标签时导航 shiny 对象的函数。如果找到了,就用一个带有新属性的新标签替换:

searchreplaceit <- function(branch, whattag, whatattribs, totag, toattribs) {
    if ("name" %in% names(branch)) {
        if ((branch$name == whattag)&&(identical( branch$attribs[names(whatattribs)], whatattribs))) {
            branch$name    <- totag
            branch$attribs <- modifyList(branch$attribs, toattribs)
        }
    }
    if (class(branch)=="shiny.tag") {
        if (length(branch$children)>0) for (i in 1: length(branch$children)) {
            if (!(is.null(branch$children[[i]]))) {
                branch$children[[i]] = searchreplaceit(branch$children[[i]], whattag, whatattribs, totag, toattribs)
        } }
    } else if (class(branch)=="list") {
        if (length(branch)>0) for (i in 1:length(branch) ) {
            if (!(is.null(branch[[i]]))) {
                branch[[i]] <- searchreplaceit(branch[[i]], whattag, whatattribs, totag, toattribs)
        } }
    } 
    return(branch)
}

例如以下内容

b <- shinydashboard::box(collapsible = T)
searchreplaceit(b, "i", list(class="fa fa-minus"), "i", list(class="XXX"))

将在 b 中搜索具有(至少)属性 "i" 的标签 class="fa fa-minus"。找到后,它会替换为标记 "i" 和属性 class="XXX"

# <div class="col-sm-6">
#   <div class="box">
#     <div class="box-header">
#       <div class="box-tools pull-right">
#         <button class="btn btn-box-tool" data-widget="collapse">
#           <i class="XXX" role="presentation" aria-label="minus icon"></i>
#         </button>
#       </div>
#     </div>
#     <div class="box-body"></div>
#   </div>
# </div>

搜索一直持续到整个对象都被扫描完毕。

唯一的难点是(1)shinyObjects 产生的对象同时交错 shiny.taglist 子对象; (2) 某些元素有时为NULL。

该函数是一个递归函数;对于访问的任何分支(类 shiny.tag 的对象)或子列表,它返回修改后的元素。