davidgohel / flextable

table farming
https://ardata-fr.github.io/flextable-book/
561 stars 81 forks source link

Inject custom css class with `htmltools_value` #633

Closed PaulinCharliquart closed 5 months ago

PaulinCharliquart commented 5 months ago

hi,

When using htmltools_value to export flextable to html, it will be nice to have an option to define additional css class. For example with a small modification of https://github.com/davidgohel/flextable/blob/HEAD/R/printers.R:

htmltools_value <- function(x, ft.align = NULL, ft.shadow = NULL,
                            extra_dependencies = NULL, custom_class="") {
  x <- flextable_global$defaults$post_process_all(x)
  x <- flextable_global$defaults$post_process_html(x)

  if (!is.null(ft.align)) {
    x$properties$align <- ft.align
  }

  caption <- caption_default_html(x)
  manual_css <- attr(caption, "css")

  list_deps <- html_dependencies_list(x)

  html_o <- tagList(
    if (length(extra_dependencies) > 0) {
      attachDependencies(
        x = tags$style(""),
        extra_dependencies
      )
    },
    attachDependencies(
      x = tags$style(""),
      list_deps
    ),
    HTML(gen_raw_html(x,
      class = paste("tabwid", custom_class),
      caption = caption,
      manual_css = manual_css
    ))
  )
  html_o
}

Expected output:

<div class="tabwid rtables">...

What do you think? I can create a pull request if need.

thanks

Paulin

davidgohel commented 5 months ago

Hello Paulin,

I don't think it's possible.

See https://davidgohel.github.io/flextable/reference/knit_print.flextable.html#html-output. Shadow dom is used to isolate rendering from the other styles (for example quarto styles). So even if your CSS class is defined, it won't influence the result.

What is doing your CSS class? What style is necessary that is not feasible with flextable API or default settings? I can help if I know what you want to achieve :)

PaulinCharliquart commented 5 months ago

Thanks for your quick reply! I will need the css class for some JavaScript functions in my shiny apps. Anyway, I found a quick solution:

 tb <- flextable::htmltools_value(ft)
 tb[[3]] <- gsub('class="tabwid"', 'class="tabwid rtables"', tb[[3]])
 tb

regards

davidgohel commented 5 months ago

If your JS functions manipulate flextable content, you can select them with .tabwid, no need to add a class for that!