Carl
Carl

Reputation: 7540

Set the class of an html table within an R function

I'd like to add a specific additional class to a table output to html by a custom R function within a Quarto document. Ideally for any df-print setting. Preferably the class would be set within the function, but failing that by the chunk option.

Something along the lines of class2 or class1 per the below failed attempt:

---
title: "reprex"
format: 
  html:
    df-print: kable
---

```{r}
#| class-output: class1

simple_function <- \() {
  knitr::kable(
    tibble::tribble(
      ~a, ~b,
      1, 2,
      3, 4
    ),
    table.attr = "class='class2'"
  )
}

simple_function()
```

Upvotes: 2

Views: 87

Answers (2)

Thierry
Thierry

Reputation: 18487

Another option is to use the classes option. This adds classes to the <div> element arround the table.

---
title: "reprex"
format: 
  html:
    df-print: kable
---

```{r}
#| classes: class1

simple_function <- \() {
  knitr::kable(
    tibble::tribble(~a, ~b, 1, 2, 3, 4)
  )
}

simple_function()
```

Upvotes: 1

Shafee
Shafee

Reputation: 20047

You need to set format='html' so that table.attr = "class='class2'" works.

---
title: "reprex"
format: 
  html:
    df-print: kable
---

```{r}
simple_function <- \() {
  knitr::kable(
    tibble::tribble(
      ~a, ~b,
      1, 2,
      3, 4
    ),
    format = 'html',
    table.attr = "class='class2'"
  )
}

simple_function()
```

Upvotes: 2

Related Questions