Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 #![doc(html_root_url = "https://docs.rs/handlebars/5.1.2")]
2 #![cfg_attr(docsrs, feature(doc_cfg))]
3 //! # Handlebars
4 //!
5 //! [Handlebars](http://handlebarsjs.com/) is a modern and extensible templating solution originally created in the JavaScript world. It's used by many popular frameworks like [Ember.js](http://emberjs.com) and Chaplin. It's also ported to some other platforms such as [Java](https://github.com/jknack/handlebars.java).
6 //!
7 //! And this is handlebars Rust implementation, designed for general purpose text generation.
8 //!
9 //! ## Quick Start
10 //!
11 //! ```
12 //! use std::collections::BTreeMap;
13 //! use handlebars::Handlebars;
14 //!
15 //! # fn main() {
16 //! // create the handlebars registry
17 //! let mut handlebars = Handlebars::new();
18 //!
19 //! // register the template. The template string will be verified and compiled.
20 //! let source = "hello {{world}}";
21 //! assert!(handlebars.register_template_string("t1", source).is_ok());
22 //!
23 //! // Prepare some data.
24 //! //
25 //! // The data type should implements `serde::Serialize`
26 //! let mut data = BTreeMap::new();
27 //! data.insert("world".to_string(), "世界!".to_string());
28 //! assert_eq!(handlebars.render("t1", &data).unwrap(), "hello 世界!");
29 //! # }
30 //! ```
31 //!
32 //! In this example, we created a template registry and registered a template named `t1`.
33 //! Then we rendered a `BTreeMap` with an entry of key `world`, the result is just what
34 //! we expected.
35 //!
36 //! I recommend you to walk through handlebars.js' [intro page](http://handlebarsjs.com)
37 //! if you are not quite familiar with the template language itself.
38 //!
39 //! ## Features
40 //!
41 //! Handlebars is a real-world templating system that you can use to build
42 //! your application without pain.
43 //!
44 //! ### Isolation of Rust and HTML
45 //!
46 //! This library doesn't attempt to use some macro magic to allow you to
47 //! write your template within your rust code. I admit that it's fun to do
48 //! that but it doesn't fit real-world use cases.
49 //!
50 //! ### Limited but essential control structures built-in
51 //!
52 //! Only essential control directives `if` and `each` are built-in. This
53 //! prevents you from putting too much application logic into your template.
54 //!
55 //! ### Extensible helper system
56 //!
57 //! Helper is the control system of handlebars language. In the original JavaScript
58 //! version, you can implement your own helper with JavaScript.
59 //!
60 //! Handlebars-rust offers similar mechanism that custom helper can be defined with
61 //! rust function, or [rhai](https://github.com/jonathandturner/rhai) script.
62 //!
63 //! The built-in helpers like `if` and `each` were written with these
64 //! helper APIs and the APIs are fully available to developers.
65 //!
66 //! ### Auto-reload in dev mode
67 //!
68 //! By turning on `dev_mode`, handlebars auto reloads any template and scripts that
69 //! loaded from files or directory. This can be handy for template development.
70 //!
71 //! ### Template inheritance
72 //!
73 //! Every time I look into a templating system, I will investigate its
74 //! support for [template inheritance][t].
75 //!
76 //! [t]: https://docs.djangoproject.com/en/3.2/ref/templates/language/#template-inheritance
77 //!
78 //! Template include is not sufficient for template reuse. In most cases
79 //! you will need a skeleton of page as parent (header, footer, etc.), and
80 //! embed your page into this parent.
81 //!
82 //! You can find a real example of template inheritance in
83 //! `examples/partials.rs` and templates used by this file.
84 //!
85 //! ### Strict mode
86 //!
87 //! Handlebars, the language designed to work with JavaScript, has no
88 //! strict restriction on accessing nonexistent fields or indexes. It
89 //! generates empty strings for such cases. However, in Rust we want to be
90 //! a little stricter sometimes.
91 //!
92 //! By enabling `strict_mode` on handlebars:
93 //!
94 //! ```
95 //! # use handlebars::Handlebars;
96 //! # let mut handlebars = Handlebars::new();
97 //! handlebars.set_strict_mode(true);
98 //! ```
99 //!
100 //! You will get a `RenderError` when accessing fields that do not exist.
101 //!
102 //! ## Limitations
103 //!
104 //! ### Compatibility with original JavaScript version
105 //!
106 //! This implementation is **not fully compatible** with the original JavaScript version.
107 //!
108 //! First of all, mustache blocks are not supported. I suggest you to use `#if` and `#each` for
109 //! the same functionality.
110 //!
111 //! Feel free to file an issue on [github](https://github.com/sunng87/handlebars-rust/issues) if
112 //! you find missing features.
113 //!
114 //! ### Types
115 //!
116 //! As a static typed language, it's a little verbose to use handlebars.
117 //! Handlebars templating language is designed against JSON data type. In rust,
118 //! we will convert user's structs, vectors or maps into Serde-Json's `Value` type
119 //! in order to use in templates. You have to make sure your data implements the
120 //! `Serialize` trait from the [Serde](https://serde.rs) project.
121 //!
122 //! ## Usage
123 //!
124 //! ### Template Creation and Registration
125 //!
126 //! Templates are created from `String`s and registered to `Handlebars` with a name.
127 //!
128 //! ```
129 //! # extern crate handlebars;
130 //!
131 //! use handlebars::Handlebars;
132 //!
133 //! # fn main() {
134 //! let mut handlebars = Handlebars::new();
135 //! let source = "hello {{world}}";
136 //!
137 //! assert!(handlebars.register_template_string("t1", source).is_ok())
138 //! # }
139 //! ```
140 //!
141 //! On registration, the template is parsed, compiled and cached in the registry. So further
142 //! usage will benefit from the one-time work. Also features like include, inheritance
143 //! that involves template reference requires you to register those template first with
144 //! a name so the registry can find it.
145 //!
146 //! If you template is small or just to experiment, you can use `render_template` API
147 //! without registration.
148 //!
149 //! ```
150 //! # use std::error::Error;
151 //! use handlebars::Handlebars;
152 //! use std::collections::BTreeMap;
153 //!
154 //! # fn main() -> Result<(), Box<dyn Error>> {
155 //! let mut handlebars = Handlebars::new();
156 //! let source = "hello {{world}}";
157 //!
158 //! let mut data = BTreeMap::new();
159 //! data.insert("world".to_string(), "世界!".to_string());
160 //! assert_eq!(handlebars.render_template(source, &data)?, "hello 世界!".to_owned());
161 //! # Ok(())
162 //! # }
163 //! ```
164 //!
165 //! #### Additional features for loading template from
166 //!
167 //! * Feature `dir_source` enables template loading
168 //! `register_templates_directory` from given directory.
169 //! * Feature `rust-embed` enables template loading
170 //! `register_embed_templates` from embedded resources in rust struct
171 //! generated with `RustEmbed`.
172 //!
173 //! ### Rendering Something
174 //!
175 //! Since handlebars is originally based on JavaScript type system. It supports dynamic features like duck-typing, truthy/falsey values. But for a static language like Rust, this is a little difficult. As a solution, we are using the `serde_json::value::Value` internally for data rendering.
176 //!
177 //! That means, if you want to render something, you have to ensure the data type implements the `serde::Serialize` trait. Most rust internal types already have that trait. Use `#derive[Serialize]` for your types to generate default implementation.
178 //!
179 //! 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`.
180 //!
181 //! ```
182 //! # use std::error::Error;
183 //! # #[macro_use]
184 //! # extern crate serde_derive;
185 //! # extern crate handlebars;
186 //!
187 //! use handlebars::Handlebars;
188 //!
189 //! #[derive(Serialize)]
190 //! struct Person {
191 //! name: String,
192 //! age: i16,
193 //! }
194 //!
195 //! # fn main() -> Result<(), Box<dyn Error>> {
196 //! let source = "Hello, {{name}}";
197 //!
198 //! let mut handlebars = Handlebars::new();
199 //! assert!(handlebars.register_template_string("hello", source).is_ok());
200 //!
201 //!
202 //! let data = Person {
203 //! name: "Ning Sun".to_string(),
204 //! age: 27
205 //! };
206 //! assert_eq!(handlebars.render("hello", &data)?, "Hello, Ning Sun".to_owned());
207 //! # Ok(())
208 //! # }
209 //! #
210 //! ```
211 //!
212 //! Or if you don't need the template to be cached or referenced by other ones, you can
213 //! simply render it without registering.
214 //!
215 //! ```
216 //! # use std::error::Error;
217 //! # #[macro_use]
218 //! # extern crate serde_derive;
219 //! # extern crate handlebars;
220 //! use handlebars::Handlebars;
221 //! # #[derive(Serialize)]
222 //! # struct Person {
223 //! # name: String,
224 //! # age: i16,
225 //! # }
226 //!
227 //! # fn main() -> Result<(), Box<dyn Error>> {
228 //! let source = "Hello, {{name}}";
229 //!
230 //! let mut handlebars = Handlebars::new();
231 //!
232 //! let data = Person {
233 //! name: "Ning Sun".to_string(),
234 //! age: 27
235 //! };
236 //! assert_eq!(handlebars.render_template("Hello, {{name}}", &data)?,
237 //! "Hello, Ning Sun".to_owned());
238 //! # Ok(())
239 //! # }
240 //! ```
241 //!
242 //! #### Escaping
243 //!
244 //! 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.
245 //!
246 //! ### Custom Helper
247 //!
248 //! 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.
249 //!
250 //! ```
251 //! use std::io::Write;
252 //! # use std::error::Error;
253 //! use handlebars::*;
254 //!
255 //! // implement by a structure impls HelperDef
256 //! #[derive(Clone, Copy)]
257 //! struct SimpleHelper;
258 //!
259 //! impl HelperDef for SimpleHelper {
260 //! fn call<'reg: 'rc, 'rc>(&self, h: &Helper, _: &Handlebars, _: &Context, rc: &mut RenderContext, out: &mut dyn Output) -> HelperResult {
261 //! let param = h.param(0).unwrap();
262 //!
263 //! out.write("1st helper: ")?;
264 //! out.write(param.value().render().as_ref())?;
265 //! Ok(())
266 //! }
267 //! }
268 //!
269 //! // implement via bare function
270 //! fn another_simple_helper (h: &Helper, _: &Handlebars, _: &Context, rc: &mut RenderContext, out: &mut dyn Output) -> HelperResult {
271 //! let param = h.param(0).unwrap();
272 //!
273 //! out.write("2nd helper: ")?;
274 //! out.write(param.value().render().as_ref())?;
275 //! Ok(())
276 //! }
277 //!
278 //!
279 //! # fn main() -> Result<(), Box<dyn Error>> {
280 //! let mut handlebars = Handlebars::new();
281 //! handlebars.register_helper("simple-helper", Box::new(SimpleHelper));
282 //! handlebars.register_helper("another-simple-helper", Box::new(another_simple_helper));
283 //! // via closure
284 //! handlebars.register_helper("closure-helper",
285 //! Box::new(|h: &Helper, r: &Handlebars, _: &Context, rc: &mut RenderContext, out: &mut dyn Output| -> HelperResult {
286 //! let param =
287 //! h.param(0).ok_or(RenderErrorReason::ParamNotFoundForIndex("closure-helper", 0))?;
288 //!
289 //! out.write("3rd helper: ")?;
290 //! out.write(param.value().render().as_ref())?;
291 //! Ok(())
292 //! }));
293 //!
294 //! let tpl = "{{simple-helper 1}}\n{{another-simple-helper 2}}\n{{closure-helper 3}}";
295 //! assert_eq!(handlebars.render_template(tpl, &())?,
296 //! "1st helper: 1\n2nd helper: 2\n3rd helper: 3".to_owned());
297 //! # Ok(())
298 //! # }
299 //!
300 //! ```
301 //!
302 //! Data available to helper can be found in [Helper](struct.Helper.html). And there are more
303 //! examples in [HelperDef](trait.HelperDef.html) page.
304 //!
305 //! You can learn more about helpers by looking into source code of built-in helpers.
306 //!
307 //!
308 //! ### Script Helper
309 //!
310 //! Like our JavaScript counterparts, handlebars allows user to define simple helpers with
311 //! a scripting language, [rhai](https://docs.rs/crate/rhai/). This can be enabled by
312 //! turning on `script_helper` feature flag.
313 //!
314 //! A sample script:
315 //!
316 //! ```handlebars
317 //! {{percent 0.34 label="%"}}
318 //! ```
319 //!
320 //! ```rhai
321 //! // percent.rhai
322 //! // get first parameter from `params` array
323 //! let value = params[0];
324 //! // get key value pair `label` from `hash` map
325 //! let label = hash["label"];
326 //!
327 //! // compute the final string presentation
328 //! (value * 100).to_string() + label
329 //! ```
330 //!
331 //! A runnable [example](https://github.com/sunng87/handlebars-rust/blob/master/examples/script.rs) can be find in the repo.
332 //!
333 //! #### Built-in Helpers
334 //!
335 //! * `{{{{raw}}}} ... {{{{/raw}}}}` escape handlebars expression within the block
336 //! * `{{#if ...}} ... {{else}} ... {{/if}}` if-else block
337 //! (See [the handlebarjs documentation](https://handlebarsjs.com/guide/builtin-helpers.html#if) on how to use this helper.)
338 //! * `{{#unless ...}} ... {{else}} .. {{/unless}}` if-not-else block
339 //! (See [the handlebarjs documentation](https://handlebarsjs.com/guide/builtin-helpers.html#unless) on how to use this helper.)
340 //! * `{{#each ...}} ... {{/each}}` iterates over an array or object. Handlebars-rust doesn't support mustache iteration syntax so use `each` instead.
341 //! (See [the handlebarjs documentation](https://handlebarsjs.com/guide/builtin-helpers.html#each) on how to use this helper.)
342 //! * `{{#with ...}} ... {{/with}}` change current context. Similar to `{{#each}}`, used for replace corresponding mustache syntax.
343 //! (See [the handlebarjs documentation](https://handlebarsjs.com/guide/builtin-helpers.html#with) on how to use this helper.)
344 //! * `{{lookup ... ...}}` get value from array by `@index` or `@key`
345 //! (See [the handlebarjs documentation](https://handlebarsjs.com/guide/builtin-helpers.html#lookup) on how to use this helper.)
346 //! * `{{> ...}}` include template by its name
347 //! * `{{log ...}}` log value with rust logger, default level: INFO. Currently you cannot change the level.
348 //! * Boolean helpers that can be used in `if` as subexpression, for example `{{#if (gt 2 1)}} ...`:
349 //! * `eq`
350 //! * `ne`
351 //! * `gt`
352 //! * `gte`
353 //! * `lt`
354 //! * `lte`
355 //! * `and`
356 //! * `or`
357 //! * `not`
358 //! * `{{len ...}}` returns length of array/object/string
359 //!
360 //! ### Template inheritance
361 //!
362 //! Handlebars.js' partial system is fully supported in this implementation.
363 //! Check [example](https://github.com/sunng87/handlebars-rust/blob/master/examples/partials.rs#L49) for details.
364 //!
365 //! ### String (or Case) Helpers
366 //!
367 //! [Handlebars] supports helpers for converting string cases for example converting a value to
368 //! 'camelCase or 'kebab-case' etc. This can be useful during generating code using Handlebars.
369 //! This can be enabled by selecting the feature-flag `string_helpers`. Currently the case
370 //! conversions from the [`heck`](https://docs.rs/heck/latest/heck) crate are supported.
371 //!
372 //! ```
373 //! # #[cfg(feature = "string_helpers")] {
374 //! # use std::error::Error;
375 //! # extern crate handlebars;
376 //! use handlebars::Handlebars;
377 //!
378 //! # fn main() -> Result<(), Box<dyn Error>> {
379 //!
380 //! let mut handlebars = Handlebars::new();
381 //!
382 //! let data = serde_json::json!({"value": "lower camel case"});
383 //! assert_eq!(handlebars.render_template("This is {{lowerCamelCase value}}", &data)?,
384 //! "This is lowerCamelCase".to_owned());
385 //! # Ok(())
386 //! # }
387 //! # }
388 //! ```
389 //!
390
391 #![allow(dead_code, clippy::upper_case_acronyms)]
392 #![warn(rust_2018_idioms)]
393 #![recursion_limit = "200"]
394
395 #[cfg(not(feature = "no_logging"))]
396 #[macro_use]
397 extern crate log;
398
399 #[macro_use]
400 extern crate pest_derive;
401 #[cfg(test)]
402 #[macro_use]
403 extern crate serde_derive;
404
405 #[allow(unused_imports)]
406 #[macro_use]
407 extern crate serde_json;
408
409 pub use self::block::{BlockContext, BlockParams};
410 pub use self::context::Context;
411 pub use self::decorators::DecoratorDef;
412 pub use self::error::{RenderError, RenderErrorReason, TemplateError, TemplateErrorReason};
413 pub use self::helpers::{HelperDef, HelperResult};
414 pub use self::json::path::Path;
415 pub use self::json::value::{to_json, JsonRender, JsonTruthy, PathAndJson, ScopedJson};
416 pub use self::local_vars::LocalVars;
417 pub use self::output::{Output, StringOutput};
418 #[cfg(feature = "dir_source")]
419 pub use self::registry::DirectorySourceOptions;
420 pub use self::registry::{html_escape, no_escape, EscapeFn, Registry as Handlebars};
421 pub use self::render::{Decorator, Evaluable, Helper, RenderContext, Renderable};
422 pub use self::template::Template;
423
424 #[doc(hidden)]
425 pub use self::serde_json::Value as JsonValue;
426
427 #[macro_use]
428 mod macros;
429 mod block;
430 mod context;
431 mod decorators;
432 mod error;
433 mod grammar;
434 mod helpers;
435 mod json;
436 mod local_vars;
437 mod output;
438 mod partial;
439 mod registry;
440 mod render;
441 mod sources;
442 mod support;
443 pub mod template;
444 mod util;