Add a "clear message" button to cookies example.

This commit is contained in:
Sergio Benitez 2023-11-01 12:08:57 -05:00
parent 654b1c3c79
commit 6f9d671321
2 changed files with 32 additions and 11 deletions

View File

@ -16,12 +16,19 @@ fn submit(cookies: &CookieJar<'_>, message: Form<&str>) -> Redirect {
Redirect::to(uri!(index))
}
#[delete("/")]
fn delete(cookies: &CookieJar<'_>) -> Redirect {
cookies.remove("message");
Redirect::to(uri!(index))
}
#[get("/")]
fn index(cookies: &CookieJar<'_>) -> Template {
let message = cookies.get("message").map(|c| c.value());
Template::render("message", context! { message })
let present = cookies.get("message").is_some();
Template::render("message", context! { present, message })
}
pub fn routes() -> Vec<rocket::Route> {
routes![submit, index]
routes![index, submit, delete]
}

View File

@ -7,18 +7,32 @@
</head>
<body>
<h1>Rocket Cookie Message</h1>
{{#if message }}
<p>{{message}}</p>
{{else}}
<p>No message yet.</p>
{{/if}}
<form action="/message" method="post" accept-charset="utf-8">
<textarea placeholder="Your message here..."
name="message" rows="10" cols="50"></textarea>
<p><input type="submit" value="Set Cookie"></p>
<p>
{{#if present}}
{{#if message}}
<b>Message:</b> <i>{{message}}</i>
{{else}}
<b>Message:</b> <i>[empty message]</i>
{{/if}}
{{else}}
<b>No message yet.</b>
{{/if}}
</p>
<form id="set" action="/message" method="post">
<textarea placeholder="Your message here..." name="message" rows="10" cols="50"></textarea>
</form>
<form id="delete" action="/message" method="post">
<input type="hidden" name="_method" value="delete" />
</form>
<p>
<input type="submit" form="set" value="Set Message" />
<input type="submit" form="delete" value="Clear Message" />
</p>
<a href="/">Home</a>
</body>
</html>