How can I add a class attribute to the `<ul>` tag in the automated table of contents in Rmarkdown?

Viewed 186

The organization that I work for has a HTML template for our website. I'm using this template as a custom HTML template in R markdown:

---
title: "My report"
output:
  html_document:
    template: my-template.html
    toc: true
---

Below is a snippet of the HTML template for our website. As with everything else in the template, the table of contents follows my organization's style guide. The HTML code for the table of contents is this:

    <div class="panel-body">
        <ul class="sidebar-items">
            <li><a href="#">header 1</a></li>
            <li><a href="#">Header 2</a></li>
            <li><a href="#">Header 3</a></li>
        </ul>
    </div>

I need to customize this template by inserting pandoc variables so that I can use it as my html template in Rmarkdown.

My problem is this: how can I do this and still keep the class="sidebar-items" attribute in the <ul> tag?

I've tried this:

    <div class="panel-body">
        <ul class="sidebar-items">
          $toc$
        </ul>
    </div>

But the result of course is an extra pair of <ul>-tags:

    <div class="panel-body">
        <ul class="sidebar-items">
          <ul>
            <li><a href="#header-1">header 1</a></li>
            <li><a href="#header-1">header 2</a></li>
            <li><a href="#header-3">header 3</a></li>
        </ul>
      </ul>
    </div>

How can I prevent this, but still include the class="sidebar-items" attribute?

I could just change it manually in the output HTML file from Rmarkdown, but the problem is that I need to create many HTML files, and I would very much like to avoid this extra manual work.

Thanks a lot for your help!

1 Answers

As @mb21 points out in the comments: there is currently no (easy) way to this via pandoc. You could use a pandoc filter to create the TOC yourself, but that would be a bit of an effort.

I suggest to either

  • post-process the HTML output,
  • add a JavaScript snippet to insert the desired classes or
  • rewrite the CSS/JS code which depends on the sidebar-items class to use a different selector.
Related