Maison  >  Questions et réponses  >  le corps du texte

Intégration de HTML généré par une fonction R

Je souhaite créer dynamiquement du HTML et restituer ce HTML In-quarto. L'application réelle consiste à insérer un iFrame, Mais pour faire simple, créons simplement une balise <img>.

Voici mon code .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

Il rend et la fonction est évidemment appelée, Mais il affiche le code html au lieu de l'image :

Je sais que c'est simple mais je ne le trouve pas. Merci beaucoup!

P粉513316221P粉513316221181 Il y a quelques jours382

répondre à tous(1)je répondrai

  • P粉883973481

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

    Il y a deux points à noter :

    • Tout d'abord, Quarto enveloppe par défaut toute sortie de bloc de code dans

       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

    répondre
    0
  • Annulerrépondre