jthomasmock / gtExtras

A Collection of Helper Functions for the gt Package.
https://jthomasmock.github.io/gtExtras/
Other
193 stars 26 forks source link

`opt_css` is not working with themes #108

Closed andreweatherman closed 10 months ago

andreweatherman commented 11 months ago

Any opt_css included in table themes will not render in because there is no reference to the table id. You can access the ID, if one is passed through, with a line like this:

table_id <- subset(gt_object[['_options']], parameter == 'table_id')$value[[1]]

My suggestion is to add a note to the documentation that makes it clear that a table id is needed to render in additional theme CSS (gt(id = 'table')). Then, add the line above that pulls in the table ID and use paste0 to conditionally build the needed css. Even if you pass through an ID, no CSS is applied because the function's opt_css does not use that ID.

This comes to mind as I am preparing to submit a PR for a table theme that I built a few months prior. In that theme, I am applying the css with this, first storing the themed table as an object and using an if statement to apply CSS if an ID is passed through.

 table <- if(!is.null(table_id)) {
      table %>%
        # remove the border from the bottom cell
        gt::opt_css(
          paste0("#", table_id, " tbody tr:last-child {border-bottom: 2px solid #ffffff00;}"),
          add = TRUE
        )
 }

As an example:

gt_reprex_theme <- function(gt_object, ...) {

  # get id, if one is passed through to use with CSS
  table_id <- subset(gt_object[['_options']], parameter == 'table_id')$value[[1]]

  table <- gt_object %>%
    opt_row_striping()

  # add css if table id is passed through
  table <- if(!is.null(table_id)) {
    table %>%
      # remove the border from the bottom cell
      opt_css(
        paste0("#", table_id, " tbody tr:last-child {border-bottom: 2px solid #ffffff00;}"),
        add = TRUE
      )

  }

  return(table)

}

This returns a table with CSS applied: mtcars %>% gt(id = 'test') %>% gt_reprex_theme() This returns a table with NO CSS applied: mtcars %>% gt() %>% gt_reprex_theme()

I have not submitted a PR for this yet but can if you want to go this route.

jthomasmock commented 10 months ago

Thanks for the detailed information! I've added some logic to insert an ID if missing and warn that it is happening.

jthomasmock commented 10 months ago

See: https://github.com/jthomasmock/gtExtras/commit/0ea9d53c673a5149f1139ee0a3cde8a7a54df0c1