title: How to use htmltools::tagList such that headers show in RMarkdown table of contents
body: <p>I need to generate multiple <code>htmlwidgets</code> within a loop in an RMarkdown document. This is accomplished using <code>htmltools::tagList</code>. The following snippet will generate HTML output with 2 level 2 headings and a datatable in each section. The only problem is that I specified <code>toc: true</code> but though <code>tags$h2(headers[i])</code> will render a level 2 headings on the page, those headings are not picked up by the table of contents. Is there a way get these headings in the TOC? </p>
  
  <pre><code>---
  output: 
    html_document:
      toc: true
  ---
  
  ## level 2 heading 0 - this one in TOC
  
  ```{r}
  library(DT)
  library(htmltools)
  
  headers &lt;- c("level 2 heading 1", "level 2 heading 2")
  html_tags &lt;- vector(mode = "list", length = 2*length(headers))
  for (i in 1:length(headers)) {
    html_tags[[(2*i)-1]] &lt;- tags$h2(headers[i])
    html_tags[[(2*i)]] &lt;- list(list(datatable(iris)))
  }
  
  tagList(html_tags)
  ```
  </code></pre>
  
  <p>Note that in the result below the heading generated using "##" shows up in the table of contents, but the headings from the <code>tagList</code> call, though they render correctly in the document, are now in the table of contents.</p>
  
  <p><a href="https://i.stack.imgur.com/gWVnT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gWVnT.png" alt="enter image description here"></a></p>