7.10 Include the content of an existing HTML file (*)

With the includes option of the html_document format (or any other formats that support this option), you can include the content of an existing HTML file in the HTML output document in three possible places: the <head> area, the beginning of <body>, and the end of </body>.

      in_header: header.html
      before_body: before.html
      after_body: after.html

If you are not familiar with HTML, Section 7.9 may help you better understand these options.

With the in_header option, you can inject CSS and JavaScript code into the <head> tag. With before_body, you may include a header that shows a banner or logo. With after_body, you can include a footer, e.g.,

<div class="footer">Copyright &copy; John Doe 2020</div>

Sometimes you may want to include the content of an external HTML file in an arbitrary place of the body, which can be done with htmltools::includeHTML(). You pass the path of the HTML file to this function. It will read the file, and write its content to the output document. You may also use the technique in Section 9.5, e.g.,

```{r, echo=FALSE, results='asis'}

Please note that you must not include the content of a full HTML file in another HTML file, but can only include an HTML fragment. A full HTML file contains the <html> tag, which cannot be embedded in another <html> tag. Below is an invalid HTML document when a full HTML document is included in another HTML document:

  <head>  </head>

  Parent HTML file.
  <!-- htmltools::includeHTML() below -->
      <head>  </head>
      Child HTML file.
  <!-- included above -->


If you run into problems when including an HTML file in an HTML output document, you may check if the HTML file contains the <html> tag.

There is an output format html_fragment in the rmarkdown package, which generates an HTML fragment instead of a full HTML document. If you want to include the compiled results of an Rmd document in another Rmd document, the former Rmd document may use the html_fragment format instead of the usual html_document.

If you want to include an Rmd or Markdown document instead of an HTML file, you may use child documents introduced in Section 16.4.