R & Knitr html output: create collapse and expand header

Use case

I use R and Knitr to create long html reports. Reports contain headers using markdown # syntax. These headings provide a good orientation for reader navigation ...

Problem

... but the reports sometimes get very long. Scrolling from start to finish takes a lot of time. Report readers are annoyed to see the entire contents of the report before reaching the relevant parts.

Question

Is there a way to implement a folding and expanding title element in Knitr? Example

Requirements

  • By default, the title should be collapsed. Only by clicking the content below should the title expand. This would help a lot to keep reports insignificant in appearance and facilitate easy and quick navigation.
  • To give the reader a backward reference to the state of the header, it will represent its state. I recommend something according to the mechanism used in Wikipedia (see image above).
+6
source share
1 answer

You can collapse elements using Javascript. The jQuery JavaScript framework makes this easy enough with the hide and show methods.

In the folder containing your Rmd template, create a subfolder named script and save the jQuery file . (You don't have to be there, but it's a reasonably standard location.)

Add this code to the top of your Rmd file.

 <script type="text/javascript" language="javascript" src="script/jquery-1.10.2.min.js"> </script> 

For Markdown, the closing tag must be on a separate line .

Alternatively, if your report will mainly be read on machines with Internet access, you you can should use the jQuery version hosted by Google.

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" > </script> 

Then add another script block for your collapsing logic. The exact implementation is up to you; there are lots of examples on the internet.

The key to simplifying the folding / extension logic is that the elements you control have a consistent class (or template for their identifiers).

+4
source

All Articles