我想动态构建 html 并渲染该 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'> %s", iUrl, iText) } let's call the function and see what appears: ```{r echo=FALSE} imageLink("https://www.united.com/8cd8323f017505df6908afc0b72b4925.svg", "united logo") ``` and now, here's what it's supposed to look like: <img src = 'https://www.united.com/8cd8323f017505df6908afc0b72b4925.svg'> united logo
它渲染了,并且该函数显然被调用了, 但它显示的是 html 代码,而不是图像:
我知道这很简单,但我找不到。非常感谢!
有两点需要注意:
首先,Quarto 默认情况下将任何代码块输出包装在
中
tag. To get the output asis you need to use the chunk optionresults: asis
.Secondly,
sprintf
(or evenprint
) returns output enclosed within quotes. So after usingresults: asis
, you would get the html tags but would also get the quotes. So you need to wrap thesprintf
withcat
to get intended results.