Create Tera filters
examples/rocket/create-tera-filter/Cargo.toml
[package] name = "tera-filter" version = "0.1.0" edition = "2021" [dependencies] rocket = "0.5" rocket_dyn_templates = { version = "0.2.0", features = ["tera"] } serde_json = "1.0.128" tera = "1.20.0"
examples/rocket/create-tera-filter/Rocket.toml
[default] port = 8001
examples/rocket/create-tera-filter/src/main.rs
#[macro_use] extern crate rocket; mod mytera; #[cfg(test)] mod tests; use rocket::response::content::RawHtml; use rocket_dyn_templates::{context, Template}; #[get("/")] fn index() -> RawHtml<&'static str> { RawHtml(r#"See <a href="/hello/Foo Bar">Foo Bar</a>."#) } #[get("/hello/<name>")] pub fn hello(name: &str) -> Template { Template::render( "index", context! { title: "Hello", name: Some(name), }, ) } #[launch] fn rocket() -> _ { rocket::build() .mount("/", routes![index, hello]) .attach(Template::custom(|engines| { mytera::customize(&mut engines.tera); })) }
examples/rocket/create-tera-filter/src/mytera.rs
use std::collections::HashMap; use rocket_dyn_templates::tera::Tera; use tera::{to_value, Result, Value}; fn my_len(val: &Value, _map: &HashMap<String, Value>) -> Result<Value> { let s = val.as_str().unwrap(); Ok(to_value(s.len()).unwrap()) } pub fn customize(tera: &mut Tera) { tera.register_filter("my_len", my_len); }
examples/rocket/create-tera-filter/src/tests.rs
use super::rocket; use rocket::http::Status; use rocket::local::blocking::Client; #[test] fn test_name() { let client = Client::tracked(rocket()).unwrap(); let response = client.get("/hello/Tera%20Rocket").dispatch(); assert_eq!(response.status(), Status::Ok); let html = response.into_string().unwrap(); assert!(html.contains("Hi Tera Rocket!")); assert!(html.contains("The name is 11 characters long.")); assert!(html.contains("My number is 11.")); } #[test] fn test_index() { let client = Client::tracked(rocket()).unwrap(); let response = client.get("/").dispatch().into_string().unwrap(); assert!(response.contains(r#"See <a href="/hello/Foo Bar">Foo Bar</a>."#)); }
examples/rocket/create-tera-filter/templates/index.html.tera
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Tera Demo - {{ title }}</title> </head> <body> <a href="/">Home</a> | <a href="/hello/Unknown">Hello</a> <h1>Hi {{ name }}!</h1> <div>The name is {{ name | length }} characters long.</div> <div>My number is {{ name | my_len }}.</div> <p>Try going to <a href="/hello/Your%20Name">/hello/Your Name</a></p> </body> </html>