1

I am trying to generate html content using a for loop, but I am having problems in how the content looks in the html.

Lets say I have a Rhtml template and I want to generate paragraphs in a for loop:

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<!--begin.rcode, echo=FALSE, message=FALSE, warning=FALSE
library(htmltools)
paragraphs = c("Paragraph1","Paragraph2","Paragraph3")
tags$div(
  for(i in paragraphs){
    print(tags$p(i))
    }
  )
end.rcode-->
</body>
</html>

The problem is that the html output is like this:

## <p>Paragraph1</p>
## <p>Paragraph2</p>
## <p>Paragraph3</p>

And what I need is just three normal html paragraphs. How can I do this using a for loop?

Bruno Guarita
  • 767
  • 10
  • 21

1 Answers1

1

Move the loop outside of tags$div.

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<!--begin.rcode, echo=FALSE, message=FALSE, warning=FALSE
library(htmltools)
paragraphs = c("Paragraph1","Paragraph2","Paragraph3")
p <- list()
for(i in paragraphs){
  p <- c(p, list(tags$p(i)))
}
tags$div(p)
end.rcode-->
</body>
</html>

html

This can also be written with purr::map.

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<!--begin.rcode, echo=FALSE, message=FALSE, warning=FALSE
library(htmltools)
paragraphs = c("Paragraph1","Paragraph2","Paragraph3")
tags$div(purrr::map(paragraphs, tags$p))
end.rcode-->
</body>
</html>
Paul
  • 8,734
  • 1
  • 26
  • 36