This is very odd, seems like an unintended interaction between DT and the <details>
element, combined with a browser difference.
The DT tables aren't rendering within <details>
because DT skips rendering if the widget's root element has zero width/height: DT/datatables.js at 9f84fb59fd99a3ca110bea7a9545ec32f2c4bf0f · rstudio/DT · GitHub. Since content within <details>
is hidden by default, it won't have any width/height, so that'd explain why the tables don't render on initial page load.
But why do the tables render in Chrome, but not Firefox/Safari? From some googling, a recent Chrome 97 update apparently changed how <details>
works. Content within collapsed <details>
elements is now rendered (but hidden) on the page so find-in-page works for the hidden content. So in Chrome 97+, the widget element is actually rendered with a non-zero width although hidden, and the DT table gets rendered correctly. The blog post links to another page that says this <details>
change is now part of the HTML spec, so Firefox/Safari may eventually work the same way.
For now, one workaround would be to expand the details by default using <details open>
, if that's an option:
<details open>
<summary>DT table</summary>
```{r}
DT::datatable(mtcars)
```
</details>
Or resize the window to trigger DT's rerender-on-resize behavior, like @smithjd found.
Or a very terrible hack, add a JavaScript script that forces DT tables within collapsed <details>
to rerender when you first expand the <details>
. Here's an R Markdown snippet that seems to work, although I haven't tested this thoroughly:
```{js, echo=FALSE}
// Work around DT tables not rendering properly within <details> elements in Firefox/Safari
document.querySelectorAll('details').forEach(el => {
el.addEventListener('toggle', () => {
const tables = el.querySelectorAll('.datatables')
tables.forEach(tbl => {
if (tbl.querySelector('table')) {
return
}
tbl.classList.remove('html-widget-static-bound')
HTMLWidgets.staticRender(tbl)
})
}, { once: true })
})
```
Ultimately, the best place to address this issue is probably in the DT package though.