diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:06:31 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:06:31 +0000 |
commit | 2ff14448863ac1a1dd9533461708e29aae170c2d (patch) | |
tree | 85b9fea2bbfe3f06473cfa381eed11f273b57c5c /vendor/handlebars/examples | |
parent | Adding debian version 1.64.0+dfsg1-1. (diff) | |
download | rustc-2ff14448863ac1a1dd9533461708e29aae170c2d.tar.xz rustc-2ff14448863ac1a1dd9533461708e29aae170c2d.zip |
Adding debian version 1.65.0+dfsg1-2.debian/1.65.0+dfsg1-2
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to '')
-rw-r--r-- | vendor/handlebars/examples/dev_mode.rs | 24 | ||||
-rw-r--r-- | vendor/handlebars/examples/error.rs | 52 | ||||
-rw-r--r-- | vendor/handlebars/examples/helper_macro.rs | 63 | ||||
-rw-r--r-- | vendor/handlebars/examples/partials.rs | 19 | ||||
-rw-r--r-- | vendor/handlebars/examples/script.rs | 7 |
5 files changed, 135 insertions, 30 deletions
diff --git a/vendor/handlebars/examples/dev_mode.rs b/vendor/handlebars/examples/dev_mode.rs index 99017474f..3256eed37 100644 --- a/vendor/handlebars/examples/dev_mode.rs +++ b/vendor/handlebars/examples/dev_mode.rs @@ -2,10 +2,9 @@ use std::sync::Arc; use handlebars::Handlebars; use serde_json::json; -use warp::{self, Filter}; +use tiny_http::{Response, Server}; -#[tokio::main] -async fn main() { +fn handlebars() -> Handlebars<'static> { let mut reg = Handlebars::new(); // enable dev mode for template reloading reg.set_dev_mode(true); @@ -14,14 +13,19 @@ async fn main() { reg.register_template_file("tpl", "./examples/dev_mode/template.hbs") .unwrap(); - let hbs = Arc::new(reg); - let route = warp::get().map(move || { + reg +} + +fn main() { + let hbs = Arc::new(handlebars()); + + let server = Server::http("127.0.0.1:3030").expect("Failed to start demo server."); + println!("Edit ./examples/dev_mode/template.hbs and request http://localhost:3030 to see the change on the fly."); + + for req in server.incoming_requests() { let result = hbs .render("tpl", &json!({"model": "t14s", "brand": "Thinkpad"})) .unwrap_or_else(|e| e.to_string()); - warp::reply::html(result) - }); - - println!("Edit ./examples/dev_mode/template.hbs and request http://localhost:3030 to see the change on the run."); - warp::serve(route).run(([127, 0, 0, 1], 3030)).await; + req.respond(Response::from_string(result)).unwrap(); + } } diff --git a/vendor/handlebars/examples/error.rs b/vendor/handlebars/examples/error.rs index 3fb874e2b..ed0f7c423 100644 --- a/vendor/handlebars/examples/error.rs +++ b/vendor/handlebars/examples/error.rs @@ -3,11 +3,44 @@ extern crate handlebars; #[macro_use] extern crate serde_json; -use std::error::Error; +use std::error::Error as StdError; -use handlebars::Handlebars; +use handlebars::{Context, Handlebars, Helper, Output, RenderContext, RenderError}; +use thiserror::Error; -fn main() -> Result<(), Box<dyn Error>> { +#[derive(Debug, Error)] +pub enum HelperError { + #[error("db error")] + DbError, + #[error("api error")] + ApiError, +} + +/// A helper that raise error according to parameters +pub fn error_helper( + h: &Helper, + _: &Handlebars, + _: &Context, + _: &mut RenderContext, + _: &mut dyn Output, +) -> Result<(), RenderError> { + let param = h + .param(0) + .ok_or(RenderError::new("Param 0 is required for error helper."))?; + match param.value().as_str() { + Some("db") => Err(RenderError::from_error( + "helper error", + HelperError::DbError, + )), + Some("api") => Err(RenderError::from_error( + "helper error", + HelperError::ApiError, + )), + _ => Ok(()), + } +} + +fn main() -> Result<(), Box<dyn StdError>> { env_logger::init(); let mut handlebars = Handlebars::new(); @@ -36,5 +69,18 @@ fn main() -> Result<(), Box<dyn Error>> { println!("{}", be1.source().unwrap()); println!("{:?}", be1.source().unwrap().source()); + // process error generated in helper + handlebars.register_helper("err", Box::new(error_helper)); + let e2 = handlebars + .render_template("{{err \"db\"}}", &json!({})) + .unwrap_err(); + // down-casting the error to user defined type + match e2.source().and_then(|e| e.downcast_ref::<HelperError>()) { + Some(HelperError::DbError) => { + println!("Detected error from helper: db error",) + } + _ => {} + } + Ok(()) } diff --git a/vendor/handlebars/examples/helper_macro.rs b/vendor/handlebars/examples/helper_macro.rs new file mode 100644 index 000000000..dcc6ea31a --- /dev/null +++ b/vendor/handlebars/examples/helper_macro.rs @@ -0,0 +1,63 @@ +use std::error::Error; + +use handlebars::{handlebars_helper, Handlebars, JsonRender}; +use serde_json::{json, Value}; +use time::format_description::parse; +use time::OffsetDateTime; + +// define a helper using helper +// a date format helper accept an `OffsetDateTime` as parameter +handlebars_helper!(date: |dt: OffsetDateTime| dt.format(&parse("[year]-[month]-[day]").unwrap()).unwrap()); + +// a helper returns number of provided parameters +handlebars_helper!(nargs: |*args| args.len()); + +// a helper joins all values, using both hash and parameters +handlebars_helper!(join: |{sep:str=","}, *args| + args.iter().map(|a| a.render()).collect::<Vec<String>>().join(sep) +); + +handlebars_helper!(isdefined: |v: Value| !v.is_null()); + +// a helper provides format +handlebars_helper!(date2: |dt: OffsetDateTime, {fmt:str = "[year]-[month]-[day]"}| + dt.format(&parse(fmt).unwrap()).unwrap() +); + +fn main() -> Result<(), Box<dyn Error>> { + // create the handlebars registry + let mut handlebars = Handlebars::new(); + + handlebars.register_helper("date", Box::new(date)); + handlebars.register_helper("date2", Box::new(date2)); + handlebars.register_helper("nargs", Box::new(nargs)); + handlebars.register_helper("join", Box::new(join)); + handlebars.register_helper("isdefined", Box::new(isdefined)); + + let data = OffsetDateTime::now_utc(); + + println!("{}", handlebars.render_template("{{date this}}", &data)?); + println!("{}", handlebars.render_template("{{date2 this}}", &data)?); + println!( + "{}", + handlebars.render_template("{{date2 this fmt=\"[day]/[month]/[year]\"}}", &data)? + ); + + println!("{}", handlebars.render_template("{{nargs 1 2 3 4}}", &())?); + + println!( + "{}", + handlebars.render_template("{{join 1 2 3 4 sep=\"|\" }}", &())? + ); + + println!( + "{}", + handlebars.render_template( + r#"{{isdefined a}} {{isdefined b}} +{{#if (isdefined a)}}a{{/if}} {{#if (isdefined b)}}b{{/if}}"#, + &json!({"a": 1}) + )? + ); + + Ok(()) +} diff --git a/vendor/handlebars/examples/partials.rs b/vendor/handlebars/examples/partials.rs index 80b20c2f7..017dd04b7 100644 --- a/vendor/handlebars/examples/partials.rs +++ b/vendor/handlebars/examples/partials.rs @@ -1,9 +1,8 @@ extern crate env_logger; extern crate handlebars; -#[macro_use] -extern crate maplit; use handlebars::Handlebars; +use serde_json::json; use std::error::Error; fn main() -> Result<(), Box<dyn Error>> { @@ -15,14 +14,14 @@ fn main() -> Result<(), Box<dyn Error>> { handlebars.register_template_file("base0", "./examples/partials/base0.hbs")?; handlebars.register_template_file("base1", "./examples/partials/base1.hbs")?; - let data0 = btreemap! { - "title".to_string() => "example 0".to_string(), - "parent".to_string() => "base0".to_string() - }; - let data1 = btreemap! { - "title".to_string() => "example 1".to_string(), - "parent".to_string() => "base1".to_string() - }; + let data0 = json!({ + "title": "example 0", + "parent": "base0" + }); + let data1 = json!({ + "title": "example 1", + "parent": "base1" + }); println!("Page 0"); println!("{}", handlebars.render("template", &data0)?); diff --git a/vendor/handlebars/examples/script.rs b/vendor/handlebars/examples/script.rs index bedd426cd..de89fa482 100644 --- a/vendor/handlebars/examples/script.rs +++ b/vendor/handlebars/examples/script.rs @@ -5,7 +5,6 @@ use std::error::Error; #[macro_use] extern crate serde_json; -#[cfg(feature = "script_helper")] fn main() -> Result<(), Box<dyn Error>> { let mut handlebars = Handlebars::new(); @@ -31,9 +30,3 @@ fn main() -> Result<(), Box<dyn Error>> { println!("{}", handlebars.render("tpl", &data)?); Ok(()) } - -#[cfg(not(feature = "script_helper"))] -fn main() -> Result<(), Box<dyn Error>> { - println!("Please enable feature flag script_helper for this example"); - Ok(()) -} |