askama icon indicating copy to clipboard operation
askama copied to clipboard

Cached methods call

Open imbolc opened this issue 4 years ago • 1 comments

It uses value of the first method call instead of calling the method each time. E.g.

use askama::Template;
use rand::prelude::*;

#[derive(Template)]
#[template(
    source = "{{ rnd.gen() }} {{ rnd.gen() }}",
    ext = "txt",
    print = "code"
)]
struct Foo {
    rnd: Rnd,
}

struct Rnd;
impl Rnd {
    fn gen(&self) -> i32 {
        rand::thread_rng().gen()
    }
}

fn main() {
    let foo = Foo { rnd: Rnd {} };
    dbg!(foo.render().unwrap());
}

Generates

"{expr0} {expr0}",
expr0 = &::askama::MarkupDisplay::new_unsafe(&(self.rnd.gen()), ::askama::Text),

As you can see {expr0} is calculated only once.

imbolc avatar Apr 19 '22 17:04 imbolc

This was added in #154. I will add a fix, that checks what kind of expression it is, to avoid that issue

vallentin avatar Apr 19 '22 18:04 vallentin