整个页面的全局隐藏/显示按钮
要使用 @Yihui 的提示来折叠 html 输出中的所有代码,您需要将以下代码粘贴到外部文件中(我将其命名为header.html
here):
编辑:我修改了功能toggle_R
以便按钮显示Hide Global
or Show Global
当点击它时。
<script type="text/javascript">
// toggle visibility of R source blocks in R Markdown output
function toggle_R() {
var x = document.getElementsByClassName('r');
if (x.length == 0) return;
function toggle_vis(o) {
var d = o.style.display;
o.style.display = (d == 'block' || d == '') ? 'none':'block';
}
for (i = 0; i < x.length; i++) {
var y = x[i];
if (y.tagName.toLowerCase() === 'pre') toggle_vis(y);
}
var elem = document.getElementById("myButton1");
if (elem.value === "Hide Global") elem.value = "Show Global";
else elem.value = "Hide Global";
}
document.write('<input onclick="toggle_R();" type="button" value="Hide Global" id="myButton1" style="position: absolute; top: 10%; right: 2%; z-index: 200"></input>')
</script>
在此脚本中,您可以直接使用以下命令修改与按钮关联的位置和 css 代码style
选项或将其添加到您的 css 文件中。我必须设置z-index
以较高的价值确保它出现在其他部门之上。
请注意,此 javascript 代码仅折叠调用的 R 代码echo=TRUE
,这归因于class="r"
在 HTML 中。这是由命令定义的var x = document.getElementsByClassName('r');
然后,您在 rmarkdown 脚本的 YAML 标头中调用此文件,如下例所示:
---
title: "Toggle R code"
author: "StatnMap"
date: '`r format(Sys.time(), "%d %B, %Y")`'
output:
bookdown::html_document2:
includes:
in_header: header.html
bookdown::gitbook:
includes:
in_header: header.html
---
Stackoverflow question
<https://stackoverflow.com/questions/45360998/code-folding-in-bookdown>
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
新编辑:每个块的本地隐藏/显示按钮
我终于找到了解决方案!
在查看正常 html 输出(无 bookdown)的代码折叠行为时,我能够将其添加到 bookdown 中。主要的javascript函数需要找到.sourceCode
班级划分与 bookdown 一起工作。然而,这也需要互补的 javascript 函数引导程序 https://getbootstrap.com/docs/3.3/javascript/, 但不是所有的。这适用于gitbook
and html_document2
.
步骤如下:
- 创建一个
js
与 Rmd 文件位于同一目录的文件夹
- 下载 JavaScript 函数
transition.js
and collapse.js
例如这里:https://github.com/twbs/bootstrap/tree/v3.3.7/js https://github.com/twbs/bootstrap/tree/v3.3.7/js并将它们存储在您的js
folder
- 在中创建一个新文件
js
名为的文件夹codefolding.js
使用以下代码。这与 rmarkdown code_folding 选项相同,但带有pre.sourceCode
添加以查找 R 代码块:
codefolding.js
code:
window.initializeCodeFolding = function(show) {
// handlers for show-all and hide all
$("#rmd-show-all-code").click(function() {
$('div.r-code-collapse').each(function() {
$(this).collapse('show');
});
});
$("#rmd-hide-all-code").click(function() {
$('div.r-code-collapse').each(function() {
$(this).collapse('hide');
});
});
// index for unique code element ids
var currentIndex = 1;
// select all R code blocks
var rCodeBlocks = $('pre.sourceCode, pre.r, pre.python, pre.bash, pre.sql, pre.cpp, pre.stan');
rCodeBlocks.each(function() {
// create a collapsable div to wrap the code in
var div = $('<div class="collapse r-code-collapse"></div>');
if (show)
div.addClass('in');
var id = 'rcode-643E0F36' + currentIndex++;
div.attr('id', id);
$(this).before(div);
$(this).detach().appendTo(div);
// add a show code button right above
var showCodeText = $('<span>' + (show ? 'Hide' : 'Code') + '</span>');
var showCodeButton = $('<button type="button" class="btn btn-default btn-xs code-folding-btn pull-right"></button>');
showCodeButton.append(showCodeText);
showCodeButton
.attr('data-toggle', 'collapse')
.attr('data-target', '#' + id)
.attr('aria-expanded', show)
.attr('aria-controls', id);
var buttonRow = $('<div class="row"></div>');
var buttonCol = $('<div class="col-md-12"></div>');
buttonCol.append(showCodeButton);
buttonRow.append(buttonCol);
div.before(buttonRow);
// update state of button on show/hide
div.on('hidden.bs.collapse', function () {
showCodeText.text('Code');
});
div.on('show.bs.collapse', function () {
showCodeText.text('Hide');
});
});
}
- 在以下 rmarkdown 脚本中,所有三个函数均按原样读取并包含在标头中,以便
js
文件夹对最终文档本身没有用。在阅读js函数时,我还添加了选项show
默认情况下代码块,但您可以选择隐藏它们hide
.
r降价代码:
---
title: "Toggle R code"
author: "StatnMap"
date: '`r format(Sys.time(), "%d %B, %Y")`'
output:
bookdown::html_document2:
includes:
in_header: header.html
bookdown::gitbook:
includes:
in_header: header.html
---
Stackoverflow question
<https://stackoverflow.com/questions/45360998/code-folding-in-bookdown>
```{r setup, include=FALSE}
# Add a common class name for every chunks
knitr::opts_chunk$set(
echo = TRUE)
```
```{r htmlTemp3, echo=FALSE, eval=TRUE}
codejs <- readr::read_lines("js/codefolding.js")
collapsejs <- readr::read_lines("js/collapse.js")
transitionjs <- readr::read_lines("js/transition.js")
htmlhead <-
paste('
<script>',
paste(transitionjs, collapse = "\n"),
'</script>
<script>',
paste(collapsejs, collapse = "\n"),
'</script>
<script>',
paste(codejs, collapse = "\n"),
'</script>
<style type="text/css">
.code-folding-btn { margin-bottom: 4px; }
.row { display: flex; }
.collapse { display: none; }
.in { display:block }
</style>
<script>
$(document).ready(function () {
window.initializeCodeFolding("show" === "show");
});
</script>
', sep = "\n")
readr::write_lines(htmlhead, path = "header.html")
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
summary(cars)
```
```{r plot}
plot(cars)
```
该脚本显示了 Rstudio 浏览器中的按钮,但效果不佳。不过,这对于 Firefox 来说是没问题的。
你会发现有一点css
在此代码中,但当然您可以使用更多 css 修改这些按钮的位置和颜色以及任何您想要的内容。
编辑:结合全局和本地按钮
编辑2017-11-13:全局代码折叠按钮与各个块按钮完美集成。功能toggle_R
最后不是必需的,但是你需要获得功能dropdown.js
在引导程序中。
调用时直接在代码块中调用全局按钮js
files:
```{r htmlTemp3, echo=FALSE, eval=TRUE}
codejs <- readr::read_lines("/mnt/Data/autoentrepreneur/js/codefolding.js")
collapsejs <- readr::read_lines("/mnt/Data/autoentrepreneur/js/collapse.js")
transitionjs <- readr::read_lines("/mnt/Data/autoentrepreneur/js/transition.js")
dropdownjs <- readr::read_lines("/mnt/Data/autoentrepreneur/js/dropdown.js")
htmlhead <- c(
paste('
<script>',
paste(transitionjs, collapse = "\n"),
'</script>
<script>',
paste(collapsejs, collapse = "\n"),
'</script>
<script>',
paste(codejs, collapse = "\n"),
'</script>
<script>',
paste(dropdownjs, collapse = "\n"),
'</script>
<style type="text/css">
.code-folding-btn { margin-bottom: 4px; }
.row { display: flex; }
.collapse { display: none; }
.in { display:block }
.pull-right > .dropdown-menu {
right: 0;
left: auto;
}
.open > .dropdown-menu {
display: block;
}
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
display: none;
float: left;
min-width: 160px;
padding: 5px 0;
margin: 2px 0 0;
font-size: 14px;
text-align: left;
list-style: none;
background-color: #fff;
-webkit-background-clip: padding-box;
background-clip: padding-box;
border: 1px solid #ccc;
border: 1px solid rgba(0,0,0,.15);
border-radius: 4px;
-webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175);
box-shadow: 0 6px 12px rgba(0,0,0,.175);
}
</style>
<script>
$(document).ready(function () {
window.initializeCodeFolding("show" === "show");
});
</script>
', sep = "\n"),
paste0('
<script>
document.write(\'<div class="btn-group pull-right" style="position: absolute; top: 20%; right: 2%; z-index: 200"><button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true" data-_extension-text-contrast=""><span>Code</span> <span class="caret"></span></button><ul class="dropdown-menu" style="min-width: 50px;"><li><a id="rmd-show-all-code" href="#">Show All Code</a></li><li><a id="rmd-hide-all-code" href="#">Hide All Code</a></li></ul></div>\')
</script>
')
)
readr::write_lines(htmlhead, path = "/mnt/Data/autoentrepreneur/header.html")
```
新的全局按钮显示一个下拉菜单,可在“显示所有代码”或“隐藏所有代码”之间进行选择。使用window.initializeCodeFolding("show" === "show")
默认情况下显示所有代码,而使用window.initializeCodeFolding("show" === "hide")
,默认隐藏所有代码。