在R中使用Plumber呈现HTML页面
我知道管道工更适合构建一个API而不是一个成熟的网站,这意味着我正在尝试用HTML显示db(mongo)的动态数据。所有的作品都很好,但是我使用的方式(从泰坦尼克号的例子中得到了很大的启发)可能不是最好的。以下是我的主页示例:在R中使用Plumber呈现HTML页面,r,R,我知道管道工更适合构建一个API而不是一个成熟的网站,这意味着我正在尝试用HTML显示db(mongo)的动态数据。所有的作品都很好,但是我使用的方式(从泰坦尼克号的例子中得到了很大的启发)可能不是最好的。以下是我的主页示例: #' Return result #' @get / #' @serializer html function(ht) { title <- "Title" body_intro <- "Welcome to R.gift!" body_mod
#' Return result
#' @get /
#' @serializer html
function(ht) {
title <- "Title"
body_intro <- "Welcome to R.gift!"
body_model <- paste("This is just a test ...page from the db with name <b>", single[1], "</b>")
body_msg <- paste("the home page title is <b>", single[2] , "</b>",
"The home page content:<b>",
single[3], "</b>",
sep = "\n")
css <- ' <link href="https://cloud.typography.com/7/css/fonts.css" rel="stylesheet">'
about <- '<a href="pages/about">about page</a>'
contact <- '<a href="pages/contact">contact page</a>'
result <- paste(
"<head>",
css,
"</head>",
"<html>",
'<div style="font-family: Giant Background A, Giant Background B;font-style: normal;font-weight: 400;font-size:20pt;">',
"<h1>", title, "</h1>",
"<body>",
body_intro, "</div>",
'<div style="font-family: Gotham A, Gotham B;font-style: normal;font-weight: 400;font-size:16pt;">',
"<p>", body_model, "</p>",
"<p>", body_msg, "</p>",
"<p>", about, "</p>",
"<p>", contact, "</p>",
"</div>",
"</body>",
"</html>",
collapse = "\n"
)
return(result)
}
但我假设这不允许我将变量传递到index.html,例如
理想的情况是像在任何模板系统中一样拥有标签。
提前谢谢 您可以尝试以下方法:
basicHTML <- "The home page title is <b> %s </b> The home page content: <b> %s </b>" # create a template in a file or in the script.
single <- c(title = "Hello World", bodyMsg = "lorem ipsum") # set up your parameters.
finalHTML <- sprintf(basicHTML, single[1], single[2])
basicHTML我的建议是放弃服务器端渲染,一切都在客户端进行。您可以使用像vue这样的前端库(如果您了解HTML和基本javascript,您可以使用vue),然后向后端发出获取所需数据的GET请求。然后使用这些数据来定制UI。这种方法让我们把重点放在数据上,前端集中在演示文稿上。谢谢您的回复!所以你会建议使用一个单独的文件,然后包括它?%s将如何直接绑定到变量?更多的信息将非常有用!使用单独的文件是维护代码的最简单方法。您可以在这里[link]()找到关于sprintf
的更多信息,目前我有单[1]单[2]等变量中的数据。那么如何生成基本html文件,如%s,然后生成变量名呢?对不起,没有收到!也许你能详细说明一下我的例子?
basicHTML <- "The home page title is <b> %s </b> The home page content: <b> %s </b>" # create a template in a file or in the script.
single <- c(title = "Hello World", bodyMsg = "lorem ipsum") # set up your parameters.
finalHTML <- sprintf(basicHTML, single[1], single[2])