Skip to content
This repository was archived by the owner on Mar 11, 2025. It is now read-only.

Conversation

@jannik4
Copy link
Contributor

@jannik4 jannik4 commented Jan 18, 2022

Fixes #284 (and #398?)

Example

use askama::Template;

#[derive(Debug, Clone)]
struct User { name: String }

impl User {
    fn ferris() -> Self { Self { name: "Ferris".to_string() } }
}

#[derive(Template)]
#[template(
    source = r#"Hello {{ user_opt.map(|user| user.name.as_str()).unwrap_or("World") }}"#,
    ext = "txt"
)]
struct ClosureTemplate<'a> {
    user_opt: Option<&'a User>,
}

#[test]
fn test_closure() {
    let user = User::ferris();
    let t = ClosureTemplate { user_opt: Some(&user) };
    assert_eq!(t.render().unwrap(), "Hello Ferris");

    let t = ClosureTemplate { user_opt: None };
    assert_eq!(t.render().unwrap(), "Hello World");
}

Drawbacks

I think the only inconvenience of the current implementation is that Copy types can cause problems in combination with the automatic borrowing, see below. This should always be fixable by a clone, in this case data.flag.clone(). (Edit: Or by using copied on the Option as mentioned by @vallentin)

The alternative would be to not automatically borrow the closure expression. But then non Copy types would not work anymore.

struct Data {
    flag: bool,
}

#[derive(Template)]
#[template(
    source = r#"{{ data_opt.map(|data| data.flag).unwrap_or(false) }}"#,
    ext = "txt"
)]
struct DataTemplate {
    data_opt: Option<Data>,
}

// error[E0308]: mismatched types
//   --> testing\tests\closures.rs:85:10
//    |
// 85 | #[derive(Template)]
//    |          ^^^^^^^^ expected `&bool`, found `bool`
//    |


#[derive(Template)]
#[template(
source = r#"{{ user_opt.map(|user| user.flag).unwrap_or(FALSE) }}"#,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I understand why FALSE is needed, but it's still possible to do the following, right?

Suggested change
source = r#"{{ user_opt.map(|user| user.flag).unwrap_or(FALSE) }}"#,
source = r#"{{ user_opt.map(|user| user.flag).copied().unwrap_or(false) }}"#,

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that should work too. I used FALSE to statically ensure that there really is a reference. But since copied only works on references, that's probably better here.

@Kijewski
Copy link
Member

Please have a look at jannik4#1. You don't need to add explicit lifetimes in all these places.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support closures in templates

3 participants