Custom CSS with knitr and markdown in R

时光怂恿深爱的人放手 提交于 2019-12-20 12:37:05

问题


I found this great tutorial on how to modify the css formatting of a HTML report created with markdown and knitr in Rstudio. The post can be found here.

I was hoping to build on this concept and mimic the layout of the page here by using the same css. I tried to simply copy/paste/combine the two css files I found when I viewed the page's source.

Any help you can lend would be greatly appreciated! This is my first attempt and doing anything CSS.


回答1:


This is the method provided by RStudio: http://www.rstudio.com/ide/docs/authoring/markdown_custom_rendering

options(rstudio.markdownToHTML = 
  function(inputFile, outputFile) {      
    require(markdown)
    markdownToHTML(inputFile, outputFile, stylesheet='custom.css')   
  }
) 

I've never been able to get that working properly so I do it a little differently:

I do this by creating the standard output file, then dropping the header and css code at the top in R:

tmp <- readLines("your.html") 
tmp <- tmp[-c(1:50)] # or however many lines it is before the css ends
write(tmp,"your.html")

Then I use pandoc to add my own css in a standalone file

system("pandoc -s -S your.html -c your.css -o output.html")



回答2:


Outside of RStudio (may work in it too - I'm not sure as I don't use it much), you can use option 'markdown.HTML.stylesheet' to set a custom style sheet. It will then import everything from your .css file into the newly created html file.

Here is an example:

## Set file names
htmlName <- "test.html"
rmdName <- gsub("html","Rmd", htmlName) 
stylesheetName <- 'style.css'

## Generate rmd file from R
sink(file = rmdName, type='output') 
    cat('\n<textarea maxlength="3000" cols="70">') 
    cat("Hello World!") 
    cat('</textarea>\n') 
sink()

## Generate style sheet from R
sink(file = stylesheetName, type='output') 
    cat("textarea {color: #a10000; }\n")
sink()

## Set knitr options and knit html
require(knitr) 
options(markdown.HTML.stylesheet = stylesheetName)
knit2html(rmdName, output = htmlName) 


来源:https://stackoverflow.com/questions/13095772/custom-css-with-knitr-and-markdown-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!