1

I need to render dynamic number of images from destination. But as the result through the loop I render several times only the last image from destination. But all images must be different.

My solution is inspired by these answers from stackoverflow

Shiny: Dynamic Number of Output Elements/Plots

dynamically add plots to web page using shiny

library(shiny)

# get all files from destination
images <- list.files("charts")
image_names <- str_replace_all(images, ".png", "")


server <- shinyServer(function(input, output) {


  output$images <- renderUI({

    image_output_list <- 
      lapply(1:length(image_names),
             function(i)
             {
               imagename = paste0(image_names[i], "_image")
               imageOutput(imagename)             

             })

    do.call(tagList, image_output_list)
  })

  observe({
    # if(is.null(input$files)) return(NULL)
    for (i in 1:length(image_names))
    {
      print(i)
      local({
        imagename <- paste0(image_names[i], "_image")
        print(imagename)
        output[[imagename]] <- 
          renderImage({
            list(src = normalizePath(paste0('charts/', image_names[i], '.png')))
          }, deleteFile = FALSE)
      })
    }
  })

})

ui <- shinyUI(fluidPage(
  titlePanel("Sidebar"),
  sidebarLayout(
    sidebarPanel(),
    mainPanel(
      uiOutput('images')
    )
  )
))

shinyApp(ui=ui,server=server)
iomedee
  • 381
  • 1
  • 14

1 Answers1

2

Could you try this:

  observe({
    for (i in 1:length(image_names))
    {
      local({
        ii <- i
        imagename <- paste0(image_names[ii], "_image")
        print(imagename)
        output[[imagename]] <- 
          renderImage({
            list(src = normalizePath(paste0('charts/', image_names[ii], '.png')))
          }, deleteFile = FALSE)
      })
    }
  })
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225