gt icon indicating copy to clipboard operation
gt copied to clipboard

table id when using `as_raw_html()`

Open mattkerlogue opened this issue 3 years ago • 2 comments

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")

mattkerlogue avatar Dec 10 '21 12:12 mattkerlogue

Sorry for the very long time in responding to this issue. The current behavior of as_raw_html(.., inline_css = FALSE) is not correct as it shouldn't omit the id. There should also be the option to retain the containing <div> (not something you need, but the option should be there nonetheless). I'm planning on improving the performance and correctness of as_raw_html(.., inline_css = TRUE) as well, and fixing this issue will be a part of that.

rich-iannone avatar Aug 16 '22 16:08 rich-iannone

Thanks @rich-iannone, update much appreciated.

mattkerlogue avatar Aug 16 '22 16:08 mattkerlogue