4

I am trying to add the following div and class to an entire Rmd file in knitr:

<div class="container">
</div>

I have created the container class using css as follows:

.container {
    box-shadow: 10px 10px 5px #888888;
    width: 70%;
    margin: 15em auto 5em;
    margin-bottom:-9em;
    margin-top:5em;
    background: #FFF;
}
.container p {
    padding-left: 14%;
    padding-right: 10%;
    text-indent : 1.25cm;
}
body {
   background: #efefef;
}

I would normally use a style.css to add this but for the MWE we'll put it in the main document body of the MW Rmd file at the end. I wrapped the entire document with the div of class container and get this output HERE. Notice the header # Hello World isn't processed as a header? Nothing within the div tags are processed as html. I can fix this by running knitr without the div container and then adding it later as seen here: (The HTML and The Rmd).

How can I add the div tags to the Rmd file directly?

<div class="container">

# Hello World
```{r setup, include=FALSE}
opts_chunk$set(cache=FALSE)
library(knitr); library(knitcitations); 
```

<style>
.container {
box-shadow: 10px 10px 5px #888888;
    width: 70%;
    margin: 15em auto 5em;
    margin-bottom:-9em;
    margin-top:5em;
    background: #FFF;
}
.container p {
    padding-left: 14%;
    padding-right: 10%;
    text-indent : 1.25cm;
}
body {
   background: #efefef;
}
</style>

</div>
Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519
  • Interestingly, leaving off the closing `` gives what I'm after. – Tyler Rinker Jan 08 '14 at 04:35
  • Most markdown processors ignore content between `
    ` tags, since it confusing to parse a mixture of markdown and HTML.
    – Ramnath Jan 11 '14 at 03:58
  • They do parse markdown between span tags, so a hack would be to use span tags and add a document hook that converts them to div. – Ramnath Jan 11 '14 at 03:59
  • @Ramnath, this sounds promising but I have read the documentation on hooks and don't quite understand how to make a hook to do this. Are you suggesting a chunk or output hook? – Tyler Rinker Jan 11 '14 at 14:57
  • @Ramnath I tried your suggestion and if I have it correct it still doesn't seem to work. It seems the way I set it up it's doing the gsub at the wrong time. – Tyler Rinker Jan 11 '14 at 18:25
  • I realized why it doesn't work. Hooks only work for Rmd -> md. You want to modify the resulting HTML. – Ramnath Jan 12 '14 at 04:37

1 Answers1

1

Use a custom template to wrap the Rmd in a <div class="container"></div>

<!DOCTYPE html>
<html>
    <head>
        <title>#!title#</title>
    </head>
    <div class="container">
        #!html_output#
    </div>
</html>

Then call the template when kniting

knit2html('document.Rmd', template='template.html', title='Page title')

This way you can also add a custom style.css to the template

junkka
  • 543
  • 7
  • 11