itsMeInMiami
itsMeInMiami

Reputation: 2763

How to pass a calculated file name back to the UI in Shiny

In my shiny server I am figuring out the name of a markdown file which I want to show in the UI. I know how to pass the file name, as a string, back to the UI but I don't now how to tell includeMarkdown() to treat the string as a file name.

My code so far is below. Any advice?

library(shiny)

fileConn<-file("hello.md")
writeLines(c("# Hello","# World"), fileConn)
close(fileConn)


ui <- fluidPage(
    includeMarkdown("hello.md"),
    br(),
    div("File name text:", textOutput("fileNameText", inline = TRUE)),
    #includeMarkdown(fileNameText) # this needs help
)

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

    selectedName <- reactive({
            paste0("hello.md") # this is actually more complicated...
    })
    
    output$fileNameText <- renderText(
        paste0(selectedName())
    )
    
}

shinyApp(ui = ui, server = server)

Upvotes: 0

Views: 80

Answers (1)

chemdork123
chemdork123

Reputation: 13843

Your example code works fine, but from your description, I am thinking your asking how to pass a different filename to includeMarkdown() that was created somewhere else in the app, correct?

The first step is to understand includeMarkdown() as a UI element that will change depending on other UI elements (and stuff that happens in server). The solution is to use a placeholder in the ui to hold the place for the includeMarkdown() element, and create that particular element in server using renderUI.

Hopefully you can follow this example. I'm using uiOutput('displayFile') to hold the place for the element that's created in server.

library(shiny)

fileConn<-file("hello.md")
writeLines(c("# Hello","# World"), fileConn)
close(fileConn)
    
fileConn1<-file("goodbye.md")
writeLines(c("# Goodbye","# Everyone!"), fileConn1)
close(fileConn1)
    
ui <- fluidPage(
  selectInput('file_selection', 'Choose Markdown File:', choices=c('hello.md','goodbye.md')),
  uiOutput('displayFile')
)

server <- function(input, output, session) {
  
  output$displayFile <- renderUI({
    includeMarkdown(input$file_selection)
  })      
}

shinyApp(ui = ui, server = server)

Upvotes: 1

Related Questions