简体   繁体   中英

How to embed an image in a cell a table using DT, R and Shiny

How can I embed an image in a cell that is generated using the DT package so that it is displayed in an app using shiny?

My example is based of this question R shiny: How do I put local images in shiny tables

The example code below doesn't display the image, but rather just the url.

# ui.R
require(shiny)
library(DT)

shinyUI(
  DT::dataTableOutput('mytable')
)

# Server.R
library(shiny)
library(DT)


dat <- data.frame(
  country = c('USA', 'China'),
  flag = c('<img src="test.png" height="52"></img>',
           '<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Flag_of_the_People%27s_Republic_of_China.svg/200px-Flag_of_the_People%27s_Republic_of_China.svg.png" height="52"></img>'
           )
)

shinyServer(function(input, output){
  output$mytable <- DT::renderDataTable({

    DT::datatable(dat)
  })
})

You can use the escape = FALSE in your DT call, as per: https://rstudio.github.io/DT/#escaping-table-content

# ui.R
require(shiny)
library(DT)

shinyUI(
  DT::dataTableOutput('mytable')
)

# Server.R
library(shiny)
library(DT)


dat <- data.frame(
  country = c('USA', 'China'),
  flag = c('<img src="test.png" height="52"></img>',
           '<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Flag_of_the_People%27s_Republic_of_China.svg/200px-Flag_of_the_People%27s_Republic_of_China.svg.png" height="52"></img>'
           )
)

shinyServer(function(input, output){
  output$mytable <- DT::renderDataTable({

    DT::datatable(dat, escape = FALSE) # HERE
  })
})

使用 DT 的图像

Minor update from 2021:

require(shiny)
library(DT)

shinyUI <- DT::dataTableOutput('mytable')


library(shiny)
library(DT)


dat <- data.frame(
  country = c('China'),
  flag = c('<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Flag_of_the_People%27s_Republic_of_China.svg/200px-Flag_of_the_People%27s_Republic_of_China.svg.png" height="52"></img>'
  )
)

#now this is a function
shinyServer <- function(input, output){
  output$mytable <- DT::renderDataTable({
    
    DT::datatable(dat, escape = FALSE) # HERE
  })
}

#minor change to make it runnable
shinyApp(shinyUI, shinyServer)

The solution which worked for me was the following: function was assigned to shinyServer shinyServer <- function instead of earlier way of using shinyServer(function(input,output)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM