rhtmlwidgets

HTML Widget not displaying in nested functions


I'm nesting functions within a function to be able to easily create content in a flexdashboard also generating markdown bits. I have a very abstract example but it does replicate the problem.

I'd be very grateful for any tips on how to make this work. Here's the problem:

1. I have three functions; two with some markdown, one with an html widget - in this case a reactable.

{r results = 'asis'}

f1 <- function(x) {
  cat("example text before", x)
}

f2 <- function(x) {
  reactable::reactable(mtcars)
}

f3 <- function(x) {
  cat("example text after", x)
}

2. When called in R Studio console, I get two outputs: one text from f1 and f3 and an html widget from f2 - THIS WORKS AS IT SHOULD.

{r results = 'asis'}

f1("test")
f2("test")
f3("test")

Works

3. Now the same functions are contained in another function and I would expect same outputs as when calling them separately as above, but it only produced one text from f1 and f3v - THE HTML WIDGET FROM F3 IS MISSING

{r results = 'asis'}

f <- function(x) {
  f1(x)
  f2(x)
  f3(x)
}

f("test")

enter image description here

I'm probably missing something obvious... Thanks for any help!


Solution

  • I commented that I thought you just needed to print the result, but that's wrong. I'm not sure exactly why...

    But here's something that works: Put all the output into a tagList object. For example, use this code in a code chunk:

    ```{r}
    
    f1 <- function(x) {
      paste("example text before", x)
    }
    
    f2 <- function(x) {
      reactable::reactable(mtcars)
    }
    
    f3 <- function(x) {
      paste("example text after", x)
    }
    
    f <- function(x) {
      htmltools::tagList(f1(x),
           f2(x),
           f3(x))
    }
    
    f("test")
    ```
    

    Notice that I don't use asis, and I don't use cat(): all the output needs to go into the entries in the list.