Skip to content

Instantly share code, notes, and snippets.

@DavZim
Created January 15, 2024 22:20
Show Gist options
  • Save DavZim/c01511cce2db14efbd12a34c18d3a93d to your computer and use it in GitHub Desktop.
Save DavZim/c01511cce2db14efbd12a34c18d3a93d to your computer and use it in GitHub Desktop.
R Plumber + HTMX
#* @assets ./public /
list()
n_clicked <- 0
#* @post /clicked
#* @serializer html
function() {
n_clicked <<- n_clicked + 1
paste0("Clicked <b>", n_clicked, "</b>\n")
}
#* @get /plot
#* @serializer html
function() {
png(filename = "plot.png", width = 400, height = 350)
plot(1:10, cumsum(rnorm(10)))
dev.off()
Sys.sleep(1)
enc <- base64enc::base64encode("plot.png")
unlink("plot.png")
paste0("<img src='data:image/png;base64,", enc, "' style='height:80%;width:80%'/>")
}
#* @get /plot2
#* @serializer html
function() {
png(filename = "plot2.png", width = 400, height = 350)
ir <- iris[sample.int(nrow(iris), 10), ]
plot(
x = ir$Petal.Length,
y = ir$Petal.Width,
cex = 3,
pch = 21,
main = "Petal Length vs. Petal Width",
)
dev.off()
enc <- base64enc::base64encode("plot2.png")
unlink("plot2.png")
paste0("<img src='data:image/png;base64,", enc, "' style='height:80%;width:80%'/>")
}
<!---public/index.html--->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<script src="https://unpkg.com/[email protected]"></script>
</head>
<body>
<h1>Hello World using plumber and HTMX from R</h1>
<div style="display:flex;flex-direction: row;align-items: flex-start; gap:20px;">
<button hx-post="/clicked" hx-swap="innerHTML">
Click Me
</button>
<div>
<p>The following plot is loaded automagically</p>
<div
hx-get="/plot"
hx-trigger="load"
style="height:400px;width:400px">
"Loading plot..."
</div>
</div>
<div>
<p>The following plot is loaded/updated on button click</p>
<button
hx-get="/plot2"
hx-swap="innerHTML show:top"
hx-target="#target-plot">
Update Plot
</button>
<div
id="target-plot"
style="height:400px;width:400px;background-color:antiquewhite;display:flex;align-items: center;justify-content: center;"></div>
</div>
</div>
</body>
</html>
library(plumber)
pr("plumber.R") |>
pr_hook("preroute", function(req) {
cat(sprintf("Routing a request for %s %s\n", req$REQUEST_METHOD, req$PATH_INFO))
}) |>
pr_run(port = 8080)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment