I’m trying to add custom JS function inside R markdown html file.
I’m expecting to see code block folding when I knit.
The function worked when I knitted with R:
{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE)
However, when I try Python in R markdown, it doesn’t work.
```{r setup, include=FALSE}
knitr::knit_engines$set(python = reticulate::eng_python)
```
<div class="fold s">
```{python}
print('hello, world')
```
</div>
Can anyone help me, please?
Below is the entire code that I used…
```{r setup, include=FALSE}
knitr::knit_engines$set(python = reticulate::eng_python)
```
```{js, echo=FALSE}
$(document).ready(function() {
$chunks = $('.fold');
$chunks.each(function () {
// add button to source code chunks
if ( $(this).hasClass('s') ) {
$('pre.r', this).prepend("<div class="showopt">Show</div><br style="line-height:22px;"/>");
$('pre.r', this).children('code').attr('class', 'folded');
}
// add button to output chunks
if ( $(this).hasClass('o') ) {
$('pre:not(.r)', this).has('code').prepend("<div class="showopt">Show Output</div><br style="line-height:22px;"/>");
$('pre:not(.r)', this).children('code:not(r)').addClass('folded');
// add button to plots
$(this).find('img').wrap('<pre class="plot"></pre>');
$('pre.plot', this).prepend("<div class="showopt">Show Plot</div><br style="line- height:22px;"/>");
$('pre.plot', this).children('img').addClass('folded');
}
});
// hide all chunks when document is loaded
$('.folded').css('display', 'none')
// function to toggle the visibility
$('.showopt').click(function() {
var label = $(this).html();
if (label.indexOf("Show") >= 0) {
$(this).html(label.replace("Show", "Hide"));
} else {
$(this).html(label.replace("Hide", "Show"));
}
$(this).siblings('code, img').slideToggle('fast', 'swing');
});
});
```
<style>
.showopt {
background-color: #004c93;
color: #FFFFFF;
width: 100px;
height: 20px;
text-align: center;
vertical-align: middle !important;
float: right;
font-family: sans-serif;
border-radius: 8px;
}
.showopt:hover {
background-color: #dfe4f2;
color: #004c93;
}
pre.plot {
background-color: white !important;
}
</style>
<div class="fold s">
```{python}
print('hello, world')
```
</div>