首页 > 解决方案 > 如何正确实现一个按钮来隐藏 RMarkdown/html 中的 R 代码

问题描述

我正在使用 RMarkdown 和我使用的一段代码为我的学生做一些练习 begore,来自 Ronak Bhatt,但它不再正确地工作了。取而代之的是正确格式的 R 代码,我有 ```r ... 就像文本输出一样。

下面我发布了所有设置以具有隐藏/取消隐藏 html 中的代码的按钮。我真的很感激任何帮助。谢谢!

在 R Markdown yaml 中,我有:

---
title: "Test"
author: "..."
date:  "`r Sys.Date()`" 
output: 
  html_document:
    includes:
      in_header: scripts/uncover.html 
...
---

在 knitr 设置中,我有:

```{r setup, include=FALSE}
uncover <- function(before, options, envir) {
     if (before) {
         id <- options$id
         button_string <- paste0("<button onclick=\"uncover('", 
                                 id, 
                                 "')\">Solução</button>")
         div_string <- paste0("<div id = '", id, 
                              "', style = 'display:none'>")
         paste(button_string, div_string, sep= "\n")
     }
     else {
         "</div><br>"
     }
 }

在脚本 unlock.html 我有:

<script>
function uncover(id) {
    var x = document.getElementById(id);
    if (x.style.display === "block") {
      x.style.display = "none";
    } else {
      x.style.display = "block";
    }
}
</script>

标签: r-markdownknitr

解决方案


在这里找到了解决方案。RMarkdown 对 HTML 很友好,只要使用得当,就会允许在 Rmarkdown 中使用原始 HTML。我没有使用您的 discover.html 文件,因为我直接在 Rmarkdown 中使用了其他 HTML 代码。

---
title: "Test"
author: "..."
date:  "`r Sys.Date()`" 
output: 
  html_document:
    includes:
      in_header: uncover.html
---
<button class="btn btn-primary" data-toggle="collapse" data-target="#BlockName"> Show/Hide </button>  
<div id="BlockName" class="collapse">  


```{r}

uncover <- function(before, options, envir) {
     if (before) {
         id <- options$id
         button_string <- paste0("<button onclick=\"uncover('", 
                                 id, 
                                 "')\">Solução</button>")
         div_string <- paste0("<div id = '", id, 
                              "', style = 'display:none'>")
         paste(button_string, div_string, sep= "\n")
     }
     else {
         "</div><br>"
     }
 }

```

</div>

推荐阅读