Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: fix code examples formatting #668

Merged
merged 2 commits into from
Aug 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
157 changes: 72 additions & 85 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,19 @@
//! use handlebars::Handlebars;
//!
//! # fn main() {
//! // create the handlebars registry
//! let mut handlebars = Handlebars::new();
//!
//! // register the template. The template string will be verified and compiled.
//! let source = "hello {{world}}";
//! assert!(handlebars.register_template_string("t1", source).is_ok());
//!
//! // Prepare some data.
//! //
//! // The data type should implements `serde::Serialize`
//! let mut data = BTreeMap::new();
//! data.insert("world".to_string(), "世界!".to_string());
//! assert_eq!(handlebars.render("t1", &data).unwrap(), "hello 世界!");
//! // create the handlebars registry
//! let mut handlebars = Handlebars::new();
//!
//! // register the template. The template string will be verified and compiled.
//! let source = "hello {{world}}";
//! assert!(handlebars.register_template_string("t1", source).is_ok());
//!
//! // Prepare some data.
//! //
//! // The data type should implements `serde::Serialize`
//! let mut data = BTreeMap::new();
//! data.insert("world".to_string(), "世界!".to_string());
//! assert_eq!(handlebars.render("t1", &data).unwrap(), "hello 世界!");
//! # }
//! ```
//!
Expand Down Expand Up @@ -126,15 +126,13 @@
//! Templates are created from `String`s and registered to `Handlebars` with a name.
//!
//! ```
//! # extern crate handlebars;
//!
//! use handlebars::Handlebars;
//!
//! # fn main() {
//! let mut handlebars = Handlebars::new();
//! let source = "hello {{world}}";
//! let mut handlebars = Handlebars::new();
//! let source = "hello {{world}}";
//!
//! assert!(handlebars.register_template_string("t1", source).is_ok())
//! assert!(handlebars.register_template_string("t1", source).is_ok())
//! # }
//! ```
//!
Expand All @@ -147,17 +145,16 @@
//! without registration.
//!
//! ```
//! # use std::error::Error;
//! use handlebars::Handlebars;
//! use std::collections::BTreeMap;
//!
//! # fn main() -> Result<(), Box<dyn Error>> {
//! let mut handlebars = Handlebars::new();
//! let source = "hello {{world}}";
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let mut handlebars = Handlebars::new();
//! let source = "hello {{world}}";
//!
//! let mut data = BTreeMap::new();
//! data.insert("world".to_string(), "世界!".to_string());
//! assert_eq!(handlebars.render_template(source, &data)?, "hello 世界!".to_owned());
//! let mut data = BTreeMap::new();
//! data.insert("world".to_string(), "世界!".to_string());
//! assert_eq!(handlebars.render_template(source, &data)?, "hello 世界!".to_owned());
//! # Ok(())
//! # }
//! ```
Expand All @@ -179,77 +176,67 @@
//! You can use default `render` function to render a template into `String`. From 0.9, there's `render_to_write` to render text into anything of `std::io::Write`.
//!
//! ```
//! # use std::error::Error;
//! # #[macro_use]
//! # extern crate serde_derive;
//! # extern crate handlebars;
//!
//! use handlebars::Handlebars;
//!
//! #[derive(Serialize)]
//! #[derive(serde::Serialize)]
//! struct Person {
//! name: String,
//! age: i16,
//! }
//!
//! # fn main() -> Result<(), Box<dyn Error>> {
//! let source = "Hello, {{name}}";
//!
//! let mut handlebars = Handlebars::new();
//! assert!(handlebars.register_template_string("hello", source).is_ok());
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let source = "Hello, {{name}}";
//!
//! let mut handlebars = Handlebars::new();
//! assert!(handlebars.register_template_string("hello", source).is_ok());
//!
//! let data = Person {
//! name: "Ning Sun".to_string(),
//! age: 27
//! };
//! assert_eq!(handlebars.render("hello", &data)?, "Hello, Ning Sun".to_owned());
//! let data = Person {
//! name: "Ning Sun".to_string(),
//! age: 27
//! };
//! assert_eq!(handlebars.render("hello", &data)?, "Hello, Ning Sun".to_owned());
//! # Ok(())
//! # }
//! #
//! ```
//!
//! Or if you don't need the template to be cached or referenced by other ones, you can
//! simply render it without registering.
//!
//! ```
//! # use std::error::Error;
//! # #[macro_use]
//! # extern crate serde_derive;
//! # extern crate handlebars;
//! use handlebars::Handlebars;
//! # #[derive(Serialize)]
//! # #[derive(serde::Serialize)]
//! # struct Person {
//! # name: String,
//! # age: i16,
//! # }
//!
//! # fn main() -> Result<(), Box<dyn Error>> {
//! let source = "Hello, {{name}}";
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let source = "Hello, {{name}}";
//!
//! let mut handlebars = Handlebars::new();
//! let mut handlebars = Handlebars::new();
//!
//! let data = Person {
//! name: "Ning Sun".to_string(),
//! age: 27
//! };
//! assert_eq!(handlebars.render_template("Hello, {{name}}", &data)?,
//! "Hello, Ning Sun".to_owned());
//! let data = Person {
//! name: "Ning Sun".to_string(),
//! age: 27
//! };
//! assert_eq!(
//! handlebars.render_template("Hello, {{name}}", &data)?,
//! "Hello, Ning Sun".to_owned()
//! );
//! # Ok(())
//! # }
//! ```
//!
//! #### Escaping
//!
//! As per the handlebars spec, output using `{{expression}}` is escaped by default (to be precise, the characters `&"<>'`=_` are replaced by their respective html / xml entities). However, since the use cases of a rust template engine are probably a bit more diverse than those of a JavaScript one, this implementation allows the user to supply a custom escape function to be used instead. For more information see the `EscapeFn` type and `Handlebars::register_escape_fn()` method. In particular, `no_escape()` can be used as the escape function if no escaping at all should be performed.
//! As per the handlebars spec, output using `{{expression}}` is escaped by default (to be precise, the characters ``&"<>'`=_`` are replaced by their respective html / xml entities). However, since the use cases of a rust template engine are probably a bit more diverse than those of a JavaScript one, this implementation allows the user to supply a custom escape function to be used instead. For more information see the `EscapeFn` type and `Handlebars::register_escape_fn()` method. In particular, `no_escape()` can be used as the escape function if no escaping at all should be performed.
//!
//! ### Custom Helper
//!
//! Handlebars is nothing without helpers. You can also create your own helpers with rust. Helpers in handlebars-rust are custom struct implements the `HelperDef` trait, concretely, the `call` function. For your convenience, most of stateless helpers can be implemented as bare functions.
//!
//! ```
//! use std::io::Write;
//! # use std::error::Error;
//! use handlebars::*;
//!
//! // implement by a structure impls HelperDef
Expand All @@ -276,27 +263,28 @@
//! }
//!
//!
//! # fn main() -> Result<(), Box<dyn Error>> {
//! let mut handlebars = Handlebars::new();
//! handlebars.register_helper("simple-helper", Box::new(SimpleHelper));
//! handlebars.register_helper("another-simple-helper", Box::new(another_simple_helper));
//! // via closure
//! handlebars.register_helper("closure-helper",
//! Box::new(|h: &Helper, r: &Handlebars, _: &Context, rc: &mut RenderContext, out: &mut dyn Output| -> HelperResult {
//! let param =
//! h.param(0).ok_or(RenderErrorReason::ParamNotFoundForIndex("closure-helper", 0))?;
//!
//! out.write("3rd helper: ")?;
//! out.write(param.value().render().as_ref())?;
//! Ok(())
//! }));
//!
//! let tpl = "{{simple-helper 1}}\n{{another-simple-helper 2}}\n{{closure-helper 3}}";
//! assert_eq!(handlebars.render_template(tpl, &())?,
//! "1st helper: 1\n2nd helper: 2\n3rd helper: 3".to_owned());
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let mut handlebars = Handlebars::new();
//! handlebars.register_helper("simple-helper", Box::new(SimpleHelper));
//! handlebars.register_helper("another-simple-helper", Box::new(another_simple_helper));
//! // via closure
//! handlebars.register_helper("closure-helper",
//! Box::new(|h: &Helper, r: &Handlebars, _: &Context, rc: &mut RenderContext, out: &mut dyn Output| -> HelperResult {
//! let param =
//! h.param(0).ok_or(RenderErrorReason::ParamNotFoundForIndex("closure-helper", 0))?;
//!
//! out.write("3rd helper: ")?;
//! out.write(param.value().render().as_ref())?;
//! Ok(())
//! }));
//!
//! let tpl = "{{simple-helper 1}}\n{{another-simple-helper 2}}\n{{closure-helper 3}}";
//! assert_eq!(
//! handlebars.render_template(tpl, &())?,
//! "1st helper: 1\n2nd helper: 2\n3rd helper: 3".to_owned()
//! );
//! # Ok(())
//! # }
//!
//! ```
//!
//! Data available to helper can be found in [Helper](struct.Helper.html). And there are more
Expand Down Expand Up @@ -371,17 +359,16 @@
//!
//! ```
//! # #[cfg(feature = "string_helpers")] {
//! # use std::error::Error;
//! # extern crate handlebars;
//! use handlebars::Handlebars;
//!
//! # fn main() -> Result<(), Box<dyn Error>> {
//!
//! let mut handlebars = Handlebars::new();
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let mut handlebars = Handlebars::new();
//!
//! let data = serde_json::json!({"value": "lower camel case"});
//! assert_eq!(handlebars.render_template("This is {{lowerCamelCase value}}", &data)?,
//! "This is lowerCamelCase".to_owned());
//! let data = serde_json::json!({"value": "lower camel case"});
//! assert_eq!(
//! handlebars.render_template("This is {{lowerCamelCase value}}", &data)?,
//! "This is lowerCamelCase".to_owned()
//! );
//! # Ok(())
//! # }
//! # }
Expand Down
19 changes: 8 additions & 11 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,24 @@
/// # Examples
///
/// ```rust
/// #[macro_use] extern crate handlebars;
/// #[macro_use] extern crate serde_json;
///
/// # use handlebars::{handlebars_helper, Handlebars};
/// # use serde_json::json;
/// handlebars_helper!(is_above_10: |x: u64| x > 10);
/// handlebars_helper!(is_above: |x: u64, { compare: u64 = 10 }| x > compare);
///
/// # fn main() {
/// #
/// let mut handlebars = handlebars::Handlebars::new();
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut handlebars = Handlebars::new();
/// handlebars.register_helper("is-above-10", Box::new(is_above_10));
/// handlebars.register_helper("is-above", Box::new(is_above));
///
/// let result = handlebars
/// .render_template("{{#if (is-above-10 12)}}great!{{else}}okay{{/if}}", &json!({}))
/// .unwrap();
/// .render_template("{{#if (is-above-10 12)}}great!{{else}}okay{{/if}}", &json!({}))?;
/// assert_eq!(&result, "great!");
///
/// let result2 = handlebars
/// .render_template("{{#if (is-above 12 compare=10)}}great!{{else}}okay{{/if}}", &json!({}))
/// .unwrap();
/// .render_template("{{#if (is-above 12 compare=10)}}great!{{else}}okay{{/if}}", &json!({}))?;
/// assert_eq!(&result2, "great!");
/// # }
/// # Ok(()) }
/// ```

#[macro_export]
Expand Down
Loading