Skip to content

Commit

Permalink
Prevent generating unused code if a block is specified
Browse files Browse the repository at this point in the history
  • Loading branch information
GuillaumeGomez authored and djc committed May 16, 2024
1 parent cec89c4 commit 2b500b8
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions askama_derive/src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -907,8 +907,11 @@ impl<'a> Generator<'a> {
let block_fragment_write = self.input.block == name && self.buf_writable.discard;

// Allow writing to the buffer if we're in the block fragment
let mut prev_buf_discard = buf.discard;
if block_fragment_write {
self.buf_writable.discard = false;
} else if self.buf_writable.discard {
prev_buf_discard = mem::replace(&mut buf.discard, true);
}

// Flush preceding whitespace according to the outer WS spec
Expand Down Expand Up @@ -984,6 +987,7 @@ impl<'a> Generator<'a> {
if block_fragment_write {
self.buf_writable.discard = true;
}
buf.discard = prev_buf_discard;

Ok(size_hint)
}
Expand Down Expand Up @@ -1825,6 +1829,7 @@ struct Buffer {
indent: u8,
// Whether the output buffer is currently at the start of a line
start: bool,
discard: bool,
}

impl Buffer {
Expand All @@ -1833,10 +1838,14 @@ impl Buffer {
buf: String::new(),
indent,
start: true,
discard: false,
}
}

fn writeln(&mut self, s: &str) -> Result<(), CompileError> {
if self.discard {
return Ok(());
}
if s == "}" {
self.dedent()?;
}
Expand All @@ -1852,6 +1861,9 @@ impl Buffer {
}

fn write(&mut self, s: &str) {
if self.discard {
return;
}
if self.start {
for _ in 0..(self.indent * 4) {
self.buf.push(' ');
Expand Down

0 comments on commit 2b500b8

Please sign in to comment.