geotheory
geotheory

Reputation: 23650

How to pass output to shiny::htmlTemplate(..)

I need to pass a variable via URL hash argument to a Shiny app that uses htmlTemplate() defined output. But ui = htmlTemplate(... line below fails with Error in eval(parse(text = piece), env) : object 'response' not found. Is it possible to pass an output from server to htmlTemplate()?

require(shiny)

page_template = '<style> h2 { color: red; } </style> <h2>{{response}}</h2>'

server = shinyServer(function(input, output, session) {
  observe({
    
    output$response = renderText({
      session$clientData$url_hash
    })
    
  })
})

ui = htmlTemplate(text_ = page_template)

shinyApp(ui, server)

I've also tried

page_template = '<style> h2 { color: red; } </style> <h2>{{renderText("response")}}</h2>'

.. which does not error the app, but output in browser does not render:

<h2><div id="outa160c30ab8f687db" class="shiny-text-output"></div></h2>

Upvotes: 1

Views: 162

Answers (1)

ismirsehregal
ismirsehregal

Reputation: 33417

We can use a custom message handler to achive this:

library(shiny)

page_template = '<div id="demo"><h2>This will be replaced</h2></div>
                  <script>
                  Shiny.addCustomMessageHandler("myClientData", function(url_hash) {
                        document.getElementById("demo").innerHTML = url_hash;
                        });
                  </script>'

server = shinyServer(function(input, output, session) {
  observe({
    # session$clientData$url_hash is empty
    session$sendCustomMessage("myClientData", as.character(tags$h2(session$clientData$url_protocol)))
  })
})

ui = htmlTemplate(text_ = page_template)

shinyApp(ui, server)

Please see this related article.

Here is an article regarding htmlTemplate in general.

Upvotes: 1

Related Questions