简体   繁体   中英

R/markdown: rendering html tags inside table

I want to create some sort of html-tag cheatsheet in [R] using markdown. I thought this would be a good idea as I could easily show the tag and the result. Turns out it is not that easy. Let's reframe the sentence: I think it should be easy, but still I am stuck when it comes to printing the results. I would really appreciate some hints:)

What I am doing right now:


    ---
    title: "HTML Cheatsheet"
    output: html_document
    ---
    
    ```{r, results="asis"}
    
    # init
    "%>%" <- magrittr::"%>%"
    
    # create table
    tbl <- dplyr::tibble(
        "TAG"="<h1></h1>",
        "EXAMPLE"="<h1>Headline</h1>",
        "RESULT"=cat("<h1>Headline</h1>"))
    
    # print table
    tbl %>%
        knitr::kable() %>%
        kableExtra::kable_styling()
    
    ```

My approah does not work. I think it's because cat("<h1>Headline</h1>") is printed directely and ruins the tibble. Probably there is a super easy solution to the problem. Unfortunately I am missing the right words to search for answers to my problem (the only results I get is 'how to print html tables in markdown')

Thanks for your expertise:)

Solution:

As nate mentioned, I had to use knitr::kable(escape=FALSE) to render the html tags. To keep the tags in non rendered form in the EXAMPLE column the only thing I had to do was escape them manually.


    ---
    title: "HTML Cheatsheet"
    output: html_document
    ---
    
    ```{r, results="asis"}
    
    # init
    "%>%" <- magrittr::"%>%"
    
    # create table
    tbl <- dplyr::tibble(
        "TAG"="<h1></h1>",
        "EXAMPLE"="\\<h1\\>Headline\\</h1\\>",
        "RESULT"=cat("<h1>Headline</h1>"))
    
    # print table
    tbl %>%
        knitr::kable(escape=FALSE) %>%
        kableExtra::kable_styling()
    
    ```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM