Table of contents in R Markdown ioslides

1.6k views Asked by At

How to add table of contents in an R Markdown presentation when rendered to ioslides_presentation?

Something like the following, but in ioslides:

---
title: ""
author: ""
date: ""
output:
  html_document:
    df_print: paged
    number_sections: yes
    theme: united
    toc: yes
    toc_float:
      collapsed: yes
      smooth_scroll: yes
---

For documents with output ioslides:

---
title: ""
author: ""
date: ""
output:
  ioslides_presentation: null
  beamer_presentation: default
  slidy_presentation: default
---
1

There are 1 answers

0
symbolrush On

Since the toc sub-option is not supported in RM arkdown ioslides, see e.g. here we have to do a workaround.

@ShKlinkenberg provides a solution here. The key is to use a JavaScript script to add this functionality.

The following standalone .Rmd example uses @ShKlinkenberg's script:

---
title: "ToC in IOslides"
output: ioslides_presentation
---

<!-- Script for adding ToC !-->
<script>
document.addEventListener('DOMContentLoaded', function() {
  TableOfContents();
}
);                        

function TableOfContents(container, output) {

var output = output || '#toc';

// Get all elements with class: section or subsection
idfromclass = document.querySelectorAll('.section, .subsection');

    // Create the list element:
    var list = document.createElement('ul');

    // Iterate through all found elements
    for(var i = 0; i < idfromclass.length; i++) {

        // Create the list item:
        var item = document.createElement('li');

        // Set its contents:
        var id = idfromclass[i].id

        // Replace - in id with whitespace
        var titleText = id.replace(/-/gi, " ");

        // Add text to list element
        item.appendChild(document.createTextNode(titleText));

        // Add subsection class
        item.className = idfromclass[i].className

        // Add it to the list:
        list.appendChild(item);
    }

// Return generated HTML to toc div in slide
document.querySelector(output).innerHTML = list.innerHTML;

// Generate instruction message if no classes are defined
if (idfromclass.length == 0) { document.querySelector(output).innerHTML = "Add {.section} or {.subsection} to slide name to generate TOC"; }  

};
</script>

## Table of content

<div id="toc"></div>

# Section 1 {.section}

## Subsection A {.subsection}

# Section 2 {.section}

This renders a table of contents as follows:

enter image description here