Skip to content

Commit

Permalink
Fix lstrip_blocks being too eager (#674)
Browse files Browse the repository at this point in the history
  • Loading branch information
mitsuhiko authored Jan 8, 2025
1 parent 6aa3337 commit 5bf03e4
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ All notable changes to MiniJinja are documented here.
iterators that were projected from objects. #663
- The `|items` filter will no longer allocate a list and instead
return an iterator. #665
- Fixed a bug that caused `lstrip_blocks` to act too eager. #674

## 2.5.0

Expand Down
17 changes: 15 additions & 2 deletions minijinja/src/compiler/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,17 @@ fn lstrip_block(s: &str) -> &str {
}
}

fn should_lstrip_block(flag: bool, marker: StartMarker) -> bool {
fn should_lstrip_block(flag: bool, marker: StartMarker, prefix: &str) -> bool {
if flag && !matches!(marker, StartMarker::Variable) {
// Only strip if we're at the start of a line
for c in prefix.chars().rev() {
if is_nl(c) {
return true;
} else if !c.is_whitespace() {
return false;
}
}
// If we get here, we're at the start of the file
return true;
}
#[cfg(feature = "custom_syntax")]
Expand Down Expand Up @@ -600,7 +609,11 @@ impl<'s> Tokenizer<'s> {
self.pending_start_marker = Some((marker, len));
match whitespace {
Whitespace::Default
if should_lstrip_block(self.ws_config.lstrip_blocks, marker) =>
if should_lstrip_block(
self.ws_config.lstrip_blocks,
marker,
&self.source[..self.current_offset + start],
) =>
{
let peeked = &self.rest()[..start];
let trimmed = lstrip_block(peeked);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"lstrip_blocks": true
}
---
[{% if true %} {% endif %}]
25 changes: 25 additions & 0 deletions minijinja/tests/snapshots/[email protected]
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
source: minijinja/tests/test_lexer.rs
description: "[{% if true %} {% endif %}]"
input_file: minijinja/tests/lexer-inputs/lstrip-blocks-keep-inline-space.txt
---
TemplateData("[")
"["
BlockStart
"{%"
Ident("if")
"if"
Ident("true")
"true"
BlockEnd
"%}"
TemplateData(" ")
" "
BlockStart
"{%"
Ident("endif")
"endif"
BlockEnd
"%}"
TemplateData("]")
"]"

0 comments on commit 5bf03e4

Please sign in to comment.