conditionally embed video in R-markdown (bookdown)

∥☆過路亽.° 提交于 2021-02-08 09:12:12

问题


If I simply copy and paste an HTML code provided by YouTube into a .Rmd file, this works fine for gitbook output. Here is an example of the code

<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>

However, I get error messages for PDF and EPUB outputs. In order to avoid this, I thought I could use conditional compilation, e.g.

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

However, this gets crossed out already in the RStudio editor for unexpected tokens. What is wrong here? Is there a way around this issue?


回答1:


Welcome to stackoverflow!

  • You are right, conditional compilation is a way to solve this. For this, we need to tell knitr whether the code chunk should be evaluated (conditional on the output format). This must be specified via the chunk option eval, not inside the code chunk.

  • Note that R cannot parse plain HTML code. Instead, you could pass HTML code as a string to cat() (which prints the string) and tell knitr to include the results using the chunk option 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>'
)
```

Note that I've also set echo = F such that the code is not printed in the output.

Fore more on knitr options, see Yihui's excellent documentation.



来源:https://stackoverflow.com/questions/63354509/conditionally-embed-video-in-r-markdown-bookdown

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