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

Support returning options from functions #452

Merged
merged 2 commits into from
Mar 29, 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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

All notable changes to MiniJinja are documented here.

## 1.0.17

- Added support for `Option<Into<Value>>` as return value from
functions. #452

## 1.0.16

- Tolerate underscores in number literals. #443
Expand Down
9 changes: 9 additions & 0 deletions minijinja/src/value/argtypes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -982,6 +982,15 @@ impl From<usize> for Value {
}
}

impl<I: Into<Value>> From<Option<I>> for Value {
fn from(value: Option<I>) -> Self {
match value {
Some(value) => value.into(),
None => Value::from(()),
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
19 changes: 18 additions & 1 deletion minijinja/tests/test_templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ use std::collections::BTreeMap;
use std::fmt::Write;
use std::{env, fs};

use insta::assert_snapshot;
use minijinja::value::{StructObject, Value};
use minijinja::{context, Environment, Error, State};
use minijinja::{context, render, Environment, Error, State};

use similar_asserts::assert_eq;

Expand Down Expand Up @@ -522,3 +523,19 @@ fn test_render_to_write_state() {
assert_eq!(state.lookup("foo"), Some(Value::from(42)));
assert_eq!(state.call_macro("bar", &[]).ok().as_deref(), Some("x"));
}

#[test]
fn test_functions() {
assert_snapshot!(
render!("{{ f() }}", f => Value::from_function(|| -> i32 { 42 })),
@"42"
);
assert_snapshot!(
render!("{{ f() }}", f => Value::from_function(|| -> Option<i32> { None })),
@"none"
);
assert_snapshot!(
render!("{{ f() }}", f => Value::from_function(|| -> Result<i32, Error> { Ok(23) })),
@"23"
);
}