首頁  >  問答  >  主體

嵌入 R 函數產生的 HTML

我想動態建立 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'>&emsp;%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'>&emsp;united logo

它渲染了,而且該函數顯然被呼叫了, 但它顯示的是 html 程式碼,而不是圖像:

我知道這很簡單,但我找不到。非常感謝!

P粉513316221P粉513316221181 天前383

全部回覆(1)我來回復

  • P粉883973481

    P粉8839734812024-04-02 11:25:43

    有兩點要注意:

    • 首先,Quarto 預設將任何程式碼區塊輸出包裝在

       tag. To get the output asis you need to use the chunk option results: asis.

    • Secondly, sprintf (or even print) returns output enclosed within quotes. So after using results: asis, you would get the html tags but would also get the quotes. So you need to wrap the sprintf with cat to get intended results.

    ---
    format: html
    ---
    
    ```{r}
    #| echo: false
    imageLink <- function(iUrl, iText) {
      cat(sprintf(" %s", iUrl, iText))
    }
    ```
    
    ```{r}
    #| 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

    回覆
    0
  • 取消回覆