Render a D3 Plot to Shiny htmlTemplate

I'm building a custom web page using shiny::htmlTemplate and would like to pass a d3 plot, but cannot get the d3 plot to render in the template. The browser renders an empty container with an id of d3, however, when I don't use htmlTemplate, but a fluidPage, the plot renders properly.

Any help would be appreciated.

# app.R

library(shiny)
library(r2d3)

# This works with a call to shinyApp(ui, server)
# ui <- fluidPage(
#   d3Output("d3")
# )

d3 <- d3Output("d3")

server <- function(input, output) {
  output$d3 <- renderD3({
    r2d3(
      data = c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20),
      script = "www/assets/d3example.js"
    )
  })
}

shinyApp(
# ui, using fluidPage this works as expected without the call to htmlTemplate
  ui =
    htmlTemplate(
      "www/index.html",
      d3 = d3
    ),
  server
)

Here's the index.html:

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <script src="shared/jquery.js" type="text/javascript"></script>
  <script src="shared/shiny.js" type="text/javascript"></script>
</head>

<body>
  {{ d3 }}
</body>

</html>

And the d3example.js

var barHeight = Math.floor(height / data.length);

svg.selectAll('rect')
    .data(data)
    .enter().append('rect')
    .attr('width', function (d) { return d * width; })
    .attr('height', barHeight)
    .attr('y', function (d, i) { return i * barHeight; })
    .attr('fill', 'steelblue');

I think you need to have {{ headContent() }} in the <head> of your template for HTML dependencies to show up. That also adds the Shiny and jQuery dependencies automatically. Try this for index.html?

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  {{ headContent() }}
</head>

<body>
  {{ d3 }}
</body>

</html>

That did it. Thanks!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.