Rocket/examples/handlebars_templates/src/main.rs

83 lines
1.9 KiB
Rust
Raw Normal View History

#![feature(proc_macro_hygiene)]
#[macro_use] extern crate rocket;
2016-10-04 00:56:43 +00:00
#[macro_use] extern crate serde_derive;
#[cfg(test)] mod tests;
use rocket::Request;
use rocket::response::Redirect;
2018-10-07 00:24:11 +00:00
use rocket_contrib::templates::{Template, handlebars};
2018-07-02 21:11:09 +00:00
#[derive(Serialize)]
struct TemplateContext {
2018-07-02 21:11:09 +00:00
title: &'static str,
name: Option<String>,
items: Vec<&'static str>,
// This key tells handlebars which template is the parent.
parent: &'static str,
}
#[get("/")]
fn index() -> Redirect {
Redirect::to("/hello/Unknown")
}
#[get("/hello/<name>")]
2018-03-24 15:43:06 +00:00
fn hello(name: String) -> Template {
2018-07-02 21:11:09 +00:00
Template::render("index", &TemplateContext {
title: "Hello",
name: Some(name),
items: vec!["One", "Two", "Three"],
parent: "layout",
})
2018-03-24 15:43:06 +00:00
}
#[get("/about")]
fn about() -> Template {
2018-07-02 21:11:09 +00:00
Template::render("about", &TemplateContext {
title: "About",
name: None,
items: vec!["Four", "Five", "Six"],
parent: "layout",
})
}
#[catch(404)]
2019-06-13 02:41:29 +00:00
fn not_found(req: &Request<'_>) -> Template {
let mut map = std::collections::HashMap::new();
Overhaul URI types. This is fairly large commit with several entangled logical changes. The primary change in this commit is to completely overhaul how URI handling in Rocket works. Prior to this commit, the `Uri` type acted as an origin API. Its parser was minimal and lenient, allowing URIs that were invalid according to RFC 7230. By contrast, the new `Uri` type brings with it a strict RFC 7230 compliant parser. The `Uri` type now represents any kind of valid URI, not simply `Origin` types. Three new URI types were introduced: * `Origin` - represents valid origin URIs * `Absolute` - represents valid absolute URIs * `Authority` - represents valid authority URIs The `Origin` type replaces `Uri` in many cases: * As fields and method inputs of `Route` * The `&Uri` request guard is now `&Origin` * The `uri!` macro produces an `Origin` instead of a `Uri` The strict nature of URI parsing cascaded into the following changes: * Several `Route` methods now `panic!` on invalid URIs * The `Rocket::mount()` method is (correctly) stricter with URIs * The `Redirect` constructors take a `TryInto<Uri>` type * Dispatching of a `LocalRequest` correctly validates URIs Overall, URIs are now properly and uniformly handled throughout Rocket's codebase, resulting in a more reliable and correct system. In addition to these URI changes, the following changes are also part of this commit: * The `LocalRequest::cloned_dispatch()` method was removed in favor of chaining `.clone().dispatch()`. * The entire Rocket codebase uses `crate` instead of `pub(crate)` as a visibility modifier. * Rocket uses the `crate_visibility_modifier` and `try_from` features. A note on unsafety: this commit introduces many uses of `unsafe` in the URI parser. All of these uses are a result of unsafely transforming byte slices (`&[u8]` or similar) into strings (`&str`). The parser ensures that these casts are safe, but of course, we must label their use `unsafe`. The parser was written to be as generic and efficient as possible and thus can parse directly from byte sources. Rocket, however, does not make use of this fact and so would be able to remove all uses of `unsafe` by parsing from an existing `&str`. This should be considered in the future. Fixes #443. Resolves #263.
2018-07-29 01:26:15 +00:00
map.insert("path", req.uri().path());
Template::render("error/404", &map)
}
2019-06-13 02:41:29 +00:00
use self::handlebars::{Helper, Handlebars, Context, RenderContext, Output, HelperResult, JsonRender};
2018-07-22 09:25:55 +00:00
fn wow_helper(
2019-06-13 02:41:29 +00:00
h: &Helper<'_, '_>,
2018-07-22 09:25:55 +00:00
_: &Handlebars,
_: &Context,
2020-06-07 05:55:44 +00:00
_: &mut RenderContext<'_, '_>,
2019-06-13 02:41:29 +00:00
out: &mut dyn Output
2018-07-22 09:25:55 +00:00
) -> HelperResult {
2017-12-29 04:52:03 +00:00
if let Some(param) = h.param(0) {
2018-07-22 09:25:55 +00:00
out.write("<b><i>")?;
out.write(&param.value().render())?;
out.write("</b></i>")?;
2017-12-29 04:52:03 +00:00
}
Ok(())
}
fn rocket() -> rocket::Rocket {
rocket::ignite()
2018-03-24 15:43:06 +00:00
.mount("/", routes![index, hello, about])
.register(catchers![not_found])
.attach(Template::custom(|engines| {
2017-12-29 04:52:03 +00:00
engines.handlebars.register_helper("wow", Box::new(wow_helper));
}))
}
fn main() {
let _ = rocket().launch();
}