How to hide code in RMarkdown, with option to see it

后端 未结 2 416
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 06:32

I\'m writing an RMarkdown document in which I\'d like to re-run some chunks (5 to 9). There\'s no need to display these chunks again, so I considered using

         


        
相关标签:
2条回答
  • 2020-12-13 07:36

    This has been made much easier with the rmarkdown package, which did not exist three years ago. Basically you just turn on "code folding": http://rmarkdown.rstudio.com/html_document_format.html#code_folding. You no longer have to write any JavaScript.

    E.g.

    ---
    title: "Habits"
    output:
      html_document:
        code_folding: hide
    ---
    
    0 讨论(0)
  • 2020-12-13 07:37

    If you add an html tag before your code you can use CSS selectors to do clever things to bits of the output - markdown handily passes the HTML through:

    <style>
    div.hidecode + pre {display: none}
    </style>
    
    <div class="hidecode"></div>
    ```{r}
    summary(cars)
    ```
    

    Here my CSS style rule matches the first <pre> tag after a <div class=hidecode> and sets it to be invisible. Markdown writes the R chunk with two <pre> tags - one for the R and one for the output, and this CSS catches the first one.

    Now you know how to match the code and output blocks in CSS, you can do all sorts of clever things with them in Javascript. You could put something in the <div class=hidecode> tag and add a click event that toggles the visibility:

    <style>
    div.hidecode + pre {display: none}
    </style>
    <script>
    doclick=function(e){
    e.nextSibling.nextSibling.style.display="block";
    }
    </script>
    
    <div class="hidecode" onclick="doclick(this);">[Show Code]</div>
    ```{r}
    summary(cars)
    ```
    

    The next step in complexity is to make the action toggle, but then you might as well use jQuery and get real funky. Or use this simple method. Let's do it with a button, but you also need a div to get your hooks into the R command PRE block, and the traversal gets a bit complicated:

    <style>
    div.hideme + pre {display: none}
    </style>
    <script>
    doclick=function(e){
    code = e.parentNode.nextSibling.nextSibling.nextSibling.nextSibling
    if(code.style.display=="block"){
     code.style.display='none';
     e.textContent="Show Code"
    }else{
     code.style.display="block";
     e.textContent="Hide Code"
    }
    }
    </script>
    
    <button class="hidecode" onclick="doclick(this);">Show Code</button>
    <div class="hideme"></div>
    ```{r}
    summary(cars)
    ```
    

    ( Note: I thought you could wrap R chunks in <div> tags:

    <div class="dosomething">
    ```{r}
    summary(cars) 
    ``` 
    </div>
    

    but that fails - anyone know why?)

    0 讨论(0)
提交回复
热议问题