Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/** This code sets up a simple comment box system styled with Tailwind CSS.
* It leverages Deno's blob storage for persistence,
* and renders an HTML form to accept new comments,
* while displaying all existing comments.
*/
import { blob } from "https://esm.town/v/std/blob";
// Key for blob storage
const COMMENTS_KEY = "comments_storage";
// HTML template for the form and comments list
const getHtml = (comments: string[]) => `
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<title>Comment Box</title>
</head>
<body class="bg-gray-100 text-gray-900 font-sans">
<div class="container mx-auto p-4">
<h1 class="text-3xl font-bold mb-4">Comment Box</h1>
<form method="POST" class="mb-4">
<textarea name="comment" rows="4" cols="50" class="w-full p-2 border border-gray-300 rounded mb-2"></textarea><br />
<button type="submit" class="bg-blue-500 text-white font-bold py-2 px-4 rounded">Submit</button>
</form>
<h2 class="text-2xl font-semibold mb-2">Previous Comments:</h2>
<ul class="list-disc pl-5">
${comments.map(comment => `<li class="mb-1">${comment}</li>`).join('')}
</ul>
</div>
</body>
</html>
`;
export default async function main(req: Request): Promise<Response> {
// Fetch existing comments
let comments: string[] = await blob.getJSON(COMMENTS_KEY) || [];
if (req.method === "POST") {
const formData = await req.formData();
const newComment = formData.get("comment")?.toString().trim();
if (newComment) {
// Append the new comment and save to blob storage
comments.push(newComment);
await blob.setJSON(COMMENTS_KEY, comments);
// Redirect to avoid resubmission on page refresh
return Response.redirect(new URL(req.url).origin);
}
}
// Return the HTML with comments
return new Response(getHtml(comments), {
headers: { "Content-Type": "text/html" }
});
}
janpaul123-valle_tmp_130746396595421232473002690954744.web.val.run
July 17, 2024