2

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!

  • Currently, pandoc doesn't support attributes on `OrderedList` in its internal AST. So the only way to add it directly to the `ul` is to post-process the output, or use a pandoc-filter to inject some `RawBlock 'html'` – mb21 Mar 18 '20 at 14:43

1 Answers1

0

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.
tarleb
  • 19,863
  • 4
  • 51
  • 80
  • Thanks for your suggestions, @tarleb! Do you have a link to a resource that explains how to insert the class by adding a JavaScript snippet? – Mikkel Petersen Mar 21 '20 at 13:40
  • 1
    https://stackoverflow.com/questions/195951/, but you'll want to use the [`querySelector`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) instead of `getElementById`. Does that help? – tarleb Mar 22 '20 at 16:01