Add a CSS class to single code chunks in RMarkdown

前端 未结 1 960
生来不讨喜
生来不讨喜 2020-11-28 12:57

Is it possible to add a CSS class to a certain code chunk?

Assume the following file:

---
title: \"Untitled\"
output: html_document
---


```{r cars}         


        
相关标签:
1条回答
  • 2020-11-28 13:26

    Edit: this feature was introduced in knitr v.1.16 (05/18/17)
    class.source and class.output options apply additional HTML classes to source and output chunks (see knitr documentation).
    To add myClass to source chunk:

    ```{r cars, class.source='myClass'}
    summary(cars)
    ```  
    

    Previous answer that inspired the class.source options (see here)
    You can add a class using the fenced_code_attributes pandoc's extension (which is intended to add attributes to the <pre> tag, see here) and a knitr output hook.

    The following example works fine:

    ---
    title: "Untitled"
      output: 
        html_document:
          md_extensions: +fenced_code_attributes
    ---
    
    ```{r, include=FALSE}
    knitr::knit_hooks$set(source = function(x, options) {
      return(paste0(
        "```{.r",
        ifelse(is.null(options$class),
          "", 
          paste0(" .", gsub(" ", " .", options$class))
        ),
        "}\n",
        x,
        "\n```"
      ))
    })
    ```
    
    ```{r cars, class="myClass1 myClass2"}
    summary(cars)
    ```
    

    After knitting this .Rmd file, the HTML document looks like this:

    <pre class="r myClass1 myClass2">
        <code>
            summary(cars)
        </code>
    </pre>
    

    The fenced_code_attributes extension is enabled by default: in standard cases, you don't need to include the line md_extensions: +fenced_code_attributes in your YAML header.

    I don't know if there's more straightforward solution using knitr.

    0 讨论(0)
提交回复
热议问题