Skip to content

Commit

Permalink
Add new "runtime values" chapter in the book
Browse files Browse the repository at this point in the history
  • Loading branch information
GuillaumeGomez committed Jan 9, 2025
1 parent 3e4be06 commit 4206409
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions book/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
35 changes: 35 additions & 0 deletions book/src/runtime.md
Original file line number Diff line number Diff line change
@@ -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)`.

0 comments on commit 4206409

Please sign in to comment.