Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

r - Add a CSS class to single code chunks in RMarkdown

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

Assume the following file:

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


```{r cars}
summary(cars)
```

I want to give the chunk labeled 'cars' a certain CSS class, e.g. .myClass. Is there any possibility like

```{r cars} {.myClass}
summary(cars)
```

or so? I am aware of hacks like wrapping the whole chunk in another <div>. I am interested in a straight forward solution.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))
    ),
    "}
",
    x,
    "
```"
  ))
})
```

```{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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...