如果我只是将 YouTube 提供的 HTML 代码复制并粘贴到 .Rmd 文件中,这对于 gitbook 输出来说效果很好。这是代码示例
<iframe width="560" height="315" src="https://www.youtube.com/embed/9AI3BkKQhn0"
frameborder="0" allow="accelerometer; autoplay; encrypted-media;
gyroscope; picture-in-picture" allowfullscreen>
</iframe>
但是,我收到 PDF 和 EPUB 输出的错误消息。为了避免这种情况,我想我可以使用条件编译,例如
```{r}
if (knitr::is_html_output(excludes = "epub")) {
<iframe width="560" height="315"
src="https://www.youtube.com/embed/9AI3BkKQhn0"
frameborder="0" allow="accelerometer; autoplay; encrypted-media;
gyroscope; picture-in-picture" allowfullscreen>
</iframe>
}
```
但是,这已在 RStudio 编辑器中因意外标记而被划掉。这里有什么问题吗?有办法解决这个问题吗?
最佳答案
欢迎来到 stackoverflow!
你说得对,条件编译就是解决这个问题的一种方法。为此,我们需要告诉 knitr 是否应该评估代码块(以输出格式为条件)。这必须通过 block 选项
eval
指定,而不是在代码块内。请注意,R 无法解析纯 HTML 代码。相反,您可以将 HTML 代码作为字符串传递给
cat()
(打印字符串),并告诉 knitr 使用 block 选项results = 'asis'
包含结果.
```{r, eval=knitr::is_html_output(excludes = "epub"), results = 'asis', echo = F}
cat(
'<iframe width="560" height="315"
src="https://www.youtube.com/embed/9AI3BkKQhn0"
frameborder="0" allow="accelerometer; autoplay; encrypted-media;
gyroscope; picture-in-picture" allowfullscreen>
</iframe>'
)
```
请注意,我还设置了 echo = F
,以便代码不会打印在输出中。
有关针织选项的更多信息,请参阅 Yihui 的精彩 documentation .
关于html - 有条件地将视频嵌入 R-markdown (bookdown),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63354509/