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 code below. The RMarkdown file looks like this:
---
title: Collapsible Panel
output:
html_document:
theme: flatly
highlight: tango
---
<p>
<a class="btn btn-primary" data-toggle="collapse" href="#collapseExample1" role="button" aria-expanded="false" aria-controls="collapseExample1">
Click For Answer
</a>
</p>
<div class="collapse" id="collapseExample1">
<div class="card card-body">
```{r}
hist(1:10)
```
</div>
</div>
And it looks like this when rendered:
This works! I can also control if the code and/or results must be shown by controlling the chunk options.
But, this is not optimal because the code is messy and ugly with all the raw html. Copy-pasting this multiple times is not ideal. The ID used collapseExample1
needs to be unique every time this code block is used.
Is there some way to package this block into a reusable unit like a function or something? I am thinking something like an R function, where I can pass in code to be evaluated (or code that don't need to be evaluated), chunk options (eval
, echo
, results
, etc..) and state of the panel (open/closed).
collapsible_panel(code=NULL,echo=TRUE,results="show",state="closed")
I have many unclear questions at this point. Can I run R chunks inside R chunks? Maybe I need to use child Rmd files? Do I need to write some custom javascript?