Home > Blockchain >  RMarkdown: Floating TOC AND TOC at the start of the report
RMarkdown: Floating TOC AND TOC at the start of the report

Time:08-08

I want to have both: a floating TOC and a TOC at the start of the report (in Rmarkdown). I think it's only possible to have one.

What I want to have

Here, I have manually added a TOC.

---
title: "Report"
author: "Anon"
date: '2022-07-20'
output: 
  html_document:
    toc: true
    toc_float: true
    toc_depth: 2
    collapsed: true
    smooth_scroll: true
---

## Table of Contents 

- R Markdown
- Including Plots



## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:



## Including Plots

You can also embed plots, for example:

Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.


I followed this question but I can either have a floating TOC OR a TOC at the beginning. I want both. It's one of the requirement by a client.

CodePudding user response:

The template that html_document uses can't do this, but it's easy to edit it to allow for both.

  1. To find the default template, use

    system.file("rmd/h/default.html", package = "rmarkdown")
    
  2. Get a copy of that file in the editor, and find these lines:

$if(toc_float)$
$else$
$if(toc)$
<div id="$idprefix$TOC">
$if(toc-title)$
<h2 id="$idprefix$toc-title">$toc-title$</h2>
$endif$
$toc$
</div>
$endif$
$endif$

Change them to

$if(toc)$
<div id="$idprefix$TOC">
$if(toc-title)$
<h2 id="$idprefix$toc-title">$toc-title$</h2>
$endif$
$toc$
</div>
$endif$

(i.e. make the block unconditional, instead of conditioning on not having toc_float set.) Save this file, e.g. to "toc2.html".

  1. In the YAML for your document, add the option to specify this template, i.e. it should be
output: 
  html_document:
    toc: true
    toc_float: true
    toc_depth: 2
    collapsed: true
    smooth_scroll: true
    template: toc2.html

That should do it!

  • Related