插入r函数中生成的html

xienkqul  于 2023-02-14  发布在  其他
关注(0)|答案(1)|浏览(144)

我想动态地构建html并以夸托格式呈现,实际的应用程序需要插入一个iFrame,但为了简单起见,我们只做一个<img>标记。
下面是我的.qmd代码:

```{r}
source("awash-functions.r")

How do you inject html text produced in an r function into a quarto document?
In R markdown, I had the function sprintf a string. That doesn't seem to work here!

Here is awash-functions.r:

imageLink <- function(iUrl, iText) {
  sprintf("<img src = '%s' width='24'>&emsp;%s", iUrl, iText)
}

let's call the function and see what appears:

imageLink("https://www.united.com/8cd8323f017505df6908afc0b72b4925.svg", "united logo")

and now, here's what it's supposed to look like:

 united logo


它会进行渲染,并且函数会被调用,但是它显示的是html代码,而不是图像:

![](https://i.stack.imgur.com/OgqT5.png)

我知道这是简单的东西,但我找不到。非常感谢!
xytpbqjk

xytpbqjk1#

有两点需要注意:

  • 首先,Quarto默认将所有代码块输出 Package 在<pre><code>标签中。要获得输出,您需要使用块选项results: asis
  • 其次,sprintf(甚至print)返回用引号括起来的输出,所以在使用results: asis之后,你会得到html标记,但也会得到引号,所以你需要用cat Package sprintf以得到预期的结果。
---
format: html
---

```{r}
#| echo: false
imageLink <- function(iUrl, iText) {
  cat(sprintf("<img src = '%s'>&emsp;%s", iUrl, iText))
}
#| echo: false
#| results: asis
imageLink("https://www.united.com/8cd8323f017505df6908afc0b72b4925.svg", "united logo")

and now, here's what it's supposed to look like:

 united logo


![](https://i.stack.imgur.com/qsJK6.png)

相关问题