djc / askama

Type-safe, compiled Jinja-like templates for Rust
Apache License 2.0
3.44k stars 218 forks source link

Mutable local variables #670

Open imbolc opened 2 years ago

imbolc commented 2 years ago

It would be useful to have mutable local variables. With {{ let mut foo }} syntax maybe?

The idea originates in the @djc comment: https://github.com/djc/askama/issues/669#issuecomment-1104853641

djc commented 2 years ago

It would be nice if we can do this without explicit syntax. Not sure if that can work...

imbolc commented 2 years ago

Wouldn't it surprise rustaceans used to immutable by default variables?

djc commented 2 years ago

Hmm, I think that wouldn't be a big deal. Remember, you're in the context of a &self method, so none of the mutability here is externally observable anyway.

imbolc commented 2 years ago

Still, with introduction mutability inside templates it could lead to bugs. E.g. let's say we have this structure:

# base.html
{{ let foo = 100 }}
{% include "inner.html" %}

# inner.html
{{ let mut foo = 0 }}
{{ foo += 1 }}
{{ foo }}

Now, let's imagine I forgot or accidentally removed {{ let mut foo = 0 }} from the inner template. With explicit mutability I get compilation error, without it foo == 101 :)