Search code examples
htmlrflexdashboard

Add HTML and javascript code to flexdashboard in R


I have the following code which creates a flexdashboard:

---
title: "Untitled"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
    runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)

And I want to insert some HTML and javascript code. I tried this

    Column
    -----------------------------------------------------------------------

    ### Block 1

    ```{r}
    <p>"This is a paragraph"</p>
    <script>
      alert("This is an alert")
    </script>
    ```

But it doesn't work. Please, could you help me with this question? Thank you.


Solution

  • You can directly type the HTML code, without chunk. You can also use the tags function of the 'htmltools' package in a chunk (or the Shiny UI functions). For JavaScript, use a js chunk.

    ---
    title: "TEST"
    output: 
      flexdashboard::flex_dashboard:
        orientation: rows
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    ```
    
    ```{r packages, include=FALSE}
    library(flexdashboard)
    library(htmltools)
    ```
    
    Page
    ====================================
    
    Row
    -----------------------------
    
    ### HTML and JavaScript
    
    <button id="btn">Click me</button>
    
    ```{js, echo=FALSE}
    $("#btn").on("click", function() {
      alert("You clicked the button!")
    })
    ```
    
    ### HTML using 'htmltools'
    
    ```{r, echo=FALSE}
    tags$button("Another button")
    ```