r-markdown - 如何正确实现一个按钮来隐藏 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>
解决方案
在这里找到了解决方案。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>
推荐阅读
- symfony - symfony 上的无效凭据
- javascript - 理想地使用 Try/Catch
- reactjs - 使用 TypeScript 推送到状态数组 React
- node.js - 何时在 Express 中使用 return next(error) 与 return res.sendStatus
- excel - 有没有办法编写一个宏来循环文本连接excel中的多行数据?
- wpf - 媒体播放器中的暂停和恢复
- javascript - 使用 Blazor 在浏览器中播放本地音频文件
- java - 如何从参数类型中提取 Mono 到上层?
- web3py - 无法在 python virtual_enviroment 中安装 web3
- python - 使用 string.decode("utf-8","ignore") 时结果错误