简体   繁体   English

使用for循环生成html内容

[英]Using for loops to generate html content

I am trying to generate html content using a for loop, but I am having problems in how the content looks in the html.我正在尝试使用 for 循环生成 html 内容,但是我在内容在 html 中的外观方面遇到了问题。

Lets say I have a Rhtml template and I want to generate paragraphs in a for loop:假设我有一个 Rhtml 模板,我想在 for 循环中生成段落:

<!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:问题是html输出是这样的:

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

And what I need is just three normal html paragraphs.而我需要的只是三个普通的 html 段落。 How can I do this using a for loop?我如何使用 for 循环来做到这一点?

Move the loop outside of tags$div .将循环移到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 .这也可以用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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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