How to change the position of the table of contents in rmarkdown?

前端 未结 2 1236
清酒与你
清酒与你 2020-12-08 22:58

With RStudio and knitr I see that I can add a TOC with the following code in my .rmd file.

----------------
output: 
  html_document:
    toc: yes
---------         


        
相关标签:
2条回答
  • 2020-12-08 23:05

    The position of the TOC is fixed in the R Markdown default HTML template. If you want to change its position in the document, you'll need to modify the template:

    1. Make a copy of the R Markdown HTML template to use as a starting point. You can find it by running this R command: system.file("rmd/h/default.html", package="rmarkdown")
    2. Move the $toc section to where you want the table of contents to appear.
    3. Save the modified template in the same folder as the document you're rendering as e.g. lowertitle.html
    4. Add template: lowertitle.html to the html_document settings.

    From the standpoint of the template, all of the document's content is an atomic unit, so it might be necessary to put any content you want to appear before the TOC in the template itself.

    0 讨论(0)
  • 2020-12-08 23:19

    You can use JQuery to relocate the TOC to an arbitrary position in the file. Simply insert a heading where you want the TOC to go, and use the ID generated by rendering the R Markdown file. For example:

    <script>
      // Move TOC to the Table of Contents heading (with id "table-of-contents")
      $(function() {
        $( "#TOC" ).insertAfter( $( "#table-of-contents" ) );
      });
    </script>
    

    A heading called "Table of Contents" somewhere in the R Markdown file will receive id "table-of-contents". The TOC has id "TOC". The Jquery bit above selects that TOC, and inserts it after the "Table of contents" heading, wherever in the document it's located.

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