【问题标题】:Knitr hook for modal莫代尔针织钩
【发布时间】:2021-01-20 11:28:04
【问题描述】:

是否可以基于钩子创建模式?代表 R 降价:

  ---
  title: "Modal hook"
  output: html_document
  ---
  
  ```{r setup, include=FALSE}
  library(bsplus)
  library(htmltools)
  library(knitr)
  knit_hooks$set(modal = function(before, options, envir) {
     # ??? 
  })
  ```
  
  This chunk creates a modal window
  
  ```{r, echo=FALSE}
     title <- "Test"
     text = "Some text."
     {
        sink("tmp.md")
        cat('\n```r\nc(1,1)\n```', sep="")
        cat('\n', text)
        sink()
     }
     id <- "m1"
    
    tagList(bs_modal(id = id, title = title, body = includeMarkdown("tmp.md")),
            bs_button(title) %>% bs_attach_modal(id_modal = id))
  ```
  

是否有可能创建一个执行相同操作的钩子:

  ```{r, modal = TRUE, title = "Test", text = "Some text."}
  c(1,1)
  ```
  

也应该适用于情节:

  ```{r, modal = TRUE, title = "Test", text = "Some text."}
  plot(1:10)
  ```
  

如果modal = TRUE,基本上所有chunk的输出都应该放在modal而不是document中。

问题是如何将钩子定义为第一个块。

【问题讨论】:

  • 我认为您需要为此修改输出挂钩;一个新的块挂钩是不够的。见yihui.org/knitr/hooks。

标签: html r r-markdown bootstrap-modal knitr


【解决方案1】:

以下似乎有效

  ```{r setup, include=FALSE}
  library(bsplus)
  library(htmltools)
  library(knitr)

  # generate a random id
  opts_hooks$set(modal = function(options) {
    if (isTRUE(options$modal)) {
      options$str_id <- stringi::stri_rand_strings(1, 20)
    }
    options
  })
  
  knit_hooks$set(modal = function(before, options, envir) {
     if (before) {
        paste0('\n<div class="modal fade" id="', options$str_id, '" tabindex="-1" role="dialog" aria-labelledby="m2-title">',
              '<div class="modal-dialog" role="document">',
              '<div class="modal-content">',
              '<div class="modal-header">',
                 '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>',
                 '<h4 class="modal-title" id="', options$str_id, '-title">', options$title, '</h4>',
              '</div><div class="modal-body">')
     } else {
        paste0('<p>', options$text, '</p></div>',
               '<div class="modal-footer"><button class="btn btn-default" data-dismiss="modal">Close</button></div>',
               '</div></div></div>',
               '<button class="btn btn-default" data-toggle="modal" data-target="#', options$str_id, '">', options$title, '</button><br/>\n')
     }
  })
  ```

现在可以使用以下方法创建模态:

```{r, modal = TRUE, title = "No code", echo=FALSE}
1:4
```

```{r, modal = TRUE, title = "A plot", text = "Some text."}
plot(1:10)
```

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多