diff --git a/book/src/SUMMARY.md b/book/src/SUMMARY.md index 3c5e22f4..5fe9b4f3 100644 --- a/book/src/SUMMARY.md +++ b/book/src/SUMMARY.md @@ -3,6 +3,7 @@ - [Introduction](./introduction.md) - [Getting started](./getting_started.md) - [Creating templates](./creating_templates.md) +- [Runtime values](./runtime.md) - [Debugging](./debugging.md) - [Configuration](./configuration.md) - [Template syntax](./template_syntax.md) diff --git a/book/src/runtime.md b/book/src/runtime.md new file mode 100644 index 00000000..d90762c9 --- /dev/null +++ b/book/src/runtime.md @@ -0,0 +1,35 @@ +# Runtime values + +It is possible to define variables at runtime and to use them in the templates using the `VALUES` +variable. To do so you need to use the `_with_values` variants of the `render` methods. It expects +an extra argument of type `Values`: + +```rust +use rinja::Values; + +let mut values = Values::new(); +// We add a new value named "name" with the value "Bibop". +values.add("name", "Bibop"); +// We add a new value named "another" with a vec. +values.add("another", vec![false]); +``` + +The `Values` type is storing data with the `Any` trait, allowing to store any type as long as it +implements this trait. + +Then to render with these values: + +```rust +TemplateStruct.render_with_values(&values).unwrap(); +``` + +And to use them in a template: + +```jinja +{% if let Ok(name) = VALUES.get::<&str>() %} + name is {{ name }} +{% endif %} +``` + +If you try to retrieve a value with the wrong type or that you didn't set, you will get an +`Err(ValueError)`.