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

Added support for shadowing variables #411

Merged
merged 3 commits into from
Dec 25, 2020
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
39 changes: 34 additions & 5 deletions askama_shared/src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -876,16 +876,34 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> {

match *var {
Target::Name(name) => {
if !self.locals.contains(&name) {
let meta = self.locals.get(&name).cloned();
djc marked this conversation as resolved.
Show resolved Hide resolved

let shadowed = matches!(&meta, Some(meta) if meta.initialized);
if shadowed {
// Need to flush the buffer if the variable is being shadowed,
// to ensure the old variable is used.
self.write_buf_writable(buf)?;
}
if shadowed || meta.is_none() {
buf.write("let ");
self.locals.insert_with_default(name);
}
buf.write(name);

self.locals.insert(name, LocalMeta::initialized());
}
Target::Tuple(ref targets) => {
let shadowed = targets
.iter()
.any(|name| matches!(self.locals.get(&name), Some(meta) if meta.initialized));
if shadowed {
// Need to flush the buffer if the variable is being shadowed,
// to ensure the old variable is used.
self.write_buf_writable(buf)?;
}

buf.write("let (");
for name in targets {
self.locals.insert_with_default(name);
self.locals.insert(name, LocalMeta::initialized());
buf.write(name);
buf.write(",");
}
Expand Down Expand Up @@ -1576,14 +1594,25 @@ impl Buffer {
}
}

#[derive(Default)]
#[derive(Clone, Default)]
struct LocalMeta {
refs: Option<String>,
initialized: bool,
}

impl LocalMeta {
fn initialized() -> Self {
Self {
refs: None,
initialized: true,
}
}

fn with_ref(refs: String) -> Self {
Self { refs: Some(refs) }
Self {
refs: Some(refs),
initialized: true,
}
}
}

Expand Down
12 changes: 11 additions & 1 deletion book/src/template_syntax.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Assignments can't be imported by other templates.

Assignments use the `let` tag:

```text
```jinja
{% let name = user.name %}
{% let len = name.len() %}

Expand All @@ -31,6 +31,16 @@ Assignments use the `let` tag:
{{ val }}
```

Like Rust, Askama also supports shadowing variables.

```jinja
{% let foo = "bar" %}
{{ foo }}

{% let foo = "baz" %}
{{ foo }}
```

For compatibility with Jinja, `set` can be used in place of `let`.

## Filters
Expand Down
22 changes: 22 additions & 0 deletions testing/templates/let-shadow.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{%- let a = 1 -%}
{%- let b -%}

{%- if cond -%}
{%- let b = 22 -%}
{{ b }}-

{%- let b = 33 -%}
{{ a }}-{{ b }}-
{%- else -%}
{%- let b = 222 -%}
{{ b }}-

{%- let b = 333 -%}
{{ a }}-{{ b }}-

{%- let (a, b) = Self::tuple() -%}
{{ a }}-{{ b }}-
{%- endif -%}

{%- let a = 11 -%}
{{ a }}-{{ b }}
21 changes: 21 additions & 0 deletions testing/tests/vars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,27 @@ fn test_let_decl() {
assert_eq!(t.render().unwrap(), "bar");
}

#[derive(Template)]
#[template(path = "let-shadow.html")]
struct LetShadowTemplate {
cond: bool,
}

impl LetShadowTemplate {
fn tuple() -> (i32, i32) {
(4, 5)
}
}

#[test]
fn test_let_shadow() {
let t = LetShadowTemplate { cond: true };
assert_eq!(t.render().unwrap(), "22-1-33-11-22");

let t = LetShadowTemplate { cond: false };
assert_eq!(t.render().unwrap(), "222-1-333-4-5-11-222");
}

#[derive(Template)]
#[template(source = "{% for v in self.0 %}{{ v }}{% endfor %}", ext = "txt")]
struct SelfIterTemplate(Vec<usize>);
Expand Down