Programatically generate tabset panels of datatables in Quarto

Programatically generate tabset panels of datatables in Quarto

Problem Description:

This question is similar, but not identical to this one.

Basically, I have a number of tables that I would like to show in tabsets using DT::datatable(). Unfortunately, I can’t figure out how.

The following code works, but I need to manually type all the code:

---
title: "Untitled"
format: html
---

```{r}
library(DT)
```
    
::: {.panel-tabset}

### table no. 1

```{r}
#| results: asis
datatable(mtcars)
```

### table no. 2

```{r}
#| results: asis
datatable(mtcars)
```
:::

The following works, but instead of datatable() uses a simple markdown table from pander which does not give the desired effect.

---
title: "Untitled"
format: html
---

```{r}
library(pander)
```
    
::: {.panel-tabset}
```{r}
#| results: asis

for(i in 1:2) {
  cat(sprintf("n### table no. %dnn", i))
  cat(pander(mtcars))
}
```
:::

The following code does not work, and I don’t know how to make it work:

---
title: "Untitled"
format: html
---

```{r}
library(DT)
```
    
::: {.panel-tabset}
```{r}
#| results: asis

for(i in 1:2) {
  cat(sprintf("n### table no. %dnn", i))
  print(datatable(mtcars))
}
```
:::

Solution – 1

This is a known issue in the context of RMarkdown. But as it turns out the solution for RMarkdown also works for Quarto.

Following this answer related to the same issue in RMarkdown [Discalimer: The answer is from me] you could achieve your desired result by first making sure that the javascript dependencies needed for DT are included in your document and by wrapping the datatable call inside htmltools::tagList:

---
title: "Untitled"
format: html
---

```{r}
library(DT)
```
    
```{r, include=FALSE}
# Init Step to make sure that the dependencies are loaded
htmltools::tagList(datatable(mtcars))
```

::: {.panel-tabset}
```{r}
#| results: asis
for(i in 1:2) {
  cat(sprintf("n### table no. %dnn", i))
  print(htmltools::tagList(datatable(mtcars)))
}
```
:::

enter image description here

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject