在RMarkdown中为单个代码块添加一个CSS类 [英] Add a CSS class to single code chunks in RMarkdown
问题描述
是否可以向某个代码块添加CSS类?
Is it possible to add a CSS class to a certain code chunk?
假设以下文件:
---
title: "Untitled"
output: html_document
---
```{r cars}
summary(cars)
```
我想给标记为cars的块指定一个CSS类,例如 .myClass
。
是否有可能像
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)
```
左右?我知道黑客喜欢包装整个块在另一个< div>
。
or so? I am aware of hacks like wrapping the whole chunk in another <div>
. I am interested in a straight forward solution.
推荐答案
您可以使用 fenced_code_attributes
pandoc的扩展(用于向< pre>
标签添加属性,请参阅此处)和 knitr
输出钩子。
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.
以下示例工作正常:
---
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)
```
在编写此 .Rmd
文件后, HTML
文档如下所示: p>
After knitting this .Rmd
file, the HTML
document looks like this:
<pre class="r myClass1 myClass2">
<code>
summary(cars)
</code>
</pre>
fenced_code_attributes
默认情况下:在标准情况下,您不需要在 YAML
头中包含 md_extensions:+ fenced_code_attributes
。
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.
我不知道是否有更简单的解决方案使用 knitr
。
I don't know if there's more straightforward solution using knitr
.
这篇关于在RMarkdown中为单个代码块添加一个CSS类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!