Frank Harrell
Frank Harrell

Reputation: 2230

R htmltools browsable HTML does not view without explicit print()

I can create HTML code in R that is wrapped with attributes using htmltools package functions. This allows html to be rendered from the console (a browser window is automatically launched) as well as in R Markdown and Quarto documents. But I can't get this to work without an explicit print(). How to make it work with an implicit print? Here is a minimal working example.

require(htmltools)

x <- readLines(textConnection('
<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
</table>'))

print.ctest <- function(x) browsable(HTML(x))

class(x) <- 'ctest'

print(x)   # opens browser
x          # does nothing

Upvotes: 3

Views: 250

Answers (1)

user12256545
user12256545

Reputation: 3012

If an object is called by its name it uses the default print method for the respective class. Convert x to HTML and call x afterwards it will implicit call print and launch the correct device ( browser)

require(htmltools)

x <- readLines(textConnection('
<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
</table>'))



class(x) # [1] "character"
x # prints character in console

x_1 <- browsable(HTML(x))
class(x_1) # [1] "html"      "character"
x_1 # shows HTML in browser without explicit print

Edit, to get the implicit print call to work with our custom class use registerS3method to link the method to the class


## change class
class(x) <- 'ctest'
## register its method
registerS3method("print", "ctest",function(x) {print(browsable(HTML(x)))} )

# now the class is recognized and our registered Method is used.
x 

Upvotes: 1

Related Questions