As I am preparing tutorials for students, I need a way to hide content in collapsible panels which can be revealed by clicking on a button. I have got this to work using the cod
Two slightly different methods are shown. Both approaches use only HTML and CSS. Here is the full working Rmd.
---
title: Accordion
output:
html_document
---
## Method 1
This method uses button.
```{css,echo=FALSE}
button.btn.collapsed:before
{
content:'+' ;
display:block;
width:15px;
}
button.btn:before
{
content:'-' ;
display:block;
width:15px;
}
```
```{r,echo=FALSE,results='hide'}
knitr::knit_hooks$set(drop1=function(before, options, envir) {
if (before) {
paste(
'',
'',
'
',
'',
'', sep = "\n")
} else {
paste("", "", sep = "\n")
}
})
```
```{r,drop1=TRUE,results="markup"}
str(iris)
```
## Method 2
This method uses a link which behaves like a button.
```{css,echo=FALSE}
[data-toggle="collapse"].collapsed .if-not-collapsed {
display: none;
}
[data-toggle="collapse"]:not(.collapsed) .if-collapsed {
display: none;
}
```
```{r,echo=FALSE,results='hide'}
knitr::knit_hooks$set(drop2=function(before, options, envir) {
if (before) {
paste(
'',
'',
'+',
'-',
'',
'
',
'',
'', sep = "\n")
} else {
paste("", "", sep = "\n")
}
})
```
```{r,drop2=TRUE,results="markup"}
str(iris)
```
Executed R chunks can be hidden in collapsible containers (collapsed by default). The containers are defined in the R chunk options using a custom knitr hook (drop1
/drop2
). The collapsible states of the container is controlled using a button or a link (looks like a button). Custom CSS is used to change text on the button for collapsed/open states.