Skip to content

table id when using as_raw_html() #858

@mattkerlogue

Description

@mattkerlogue

I've been using {gt} for a lot of internal reports, and relying on external styling of the output via a separate CSS file, as such I use as_raw_html(inline_css = FALSE) at the end of a {gt} pipeline to output just the HTML table.

In a live project I've had some trouble with one specific table that needs to be handled slightly differently to the main CSS file's style definitions. I hoped that setting gt(id = "special-table") would result in the id coming through to the output HTML, but it seems the id is inserted in a containing <div> (which makes sense for the general usage).

As referenced in #816, I'm actually using v0.2.2 because I'm wanting to apply custom styling (to {gt} generated classes) and later versions enclose the table within a <div> that includes style information which overrides the external stylesheet. By using v0.2.2 the object at the end of my pipeline is not contained within its own <div>, it's the raw <table> object (a behaviour I'd like to retain). I wondered if it is possible however to get the id applied to the table object when using as_raw_html().

The code:

library(gt) # v0.2.2

gtcars |> 
  gt(id = "test-table") |> 
  as_raw_html(inline_css = FALSE)

Produces:

<table class="gt_table">
  
  <thead class="gt_col_headings">
    <tr>
      <th class="gt_col_heading gt_columns_bottom_border gt_left" rowspan="1" colspan="1">mfr</th>
      <th class="gt_col_heading gt_columns_bottom_border gt_left" rowspan="1" colspan="1">model</th>
...

I'd hope for something like:

<table class="gt_table" id="test-table">
  
  <thead class="gt_col_headings">
    <tr>
      <th class="gt_col_heading gt_columns_bottom_border gt_left" rowspan="1" colspan="1">mfr</th>
      <th class="gt_col_heading gt_columns_bottom_border gt_left" rowspan="1" colspan="1">model</th>

Current less-than-ideal-hacky-workaround:

library(gt) #v0.2.2

add_tab_id <- function(x, id) {
  x <- gsub("(<table class=\"gt_table\")(>)", 
            paste0("\\1 id=\"",id,"\"\\2"),
            x)
  htmltools::HTML(x)
}

gtcars |> 
  gt() |> 
  as_raw_html(inline_css = FALSE) |>
  add_tab_id(id = "test-table")

Metadata

Metadata

Assignees

Type

No type

Projects

Status

Done

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions