Skip to content

Commit 551df78

Browse files
committed
fix: trim at most one line directives #472
1 parent 7959ee6 commit 551df78

File tree

3 files changed

+44
-5
lines changed

3 files changed

+44
-5
lines changed

src/grammar.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,17 @@ pub(crate) fn newline_matcher(c: char) -> bool {
1414
c == '\n' || c == '\r'
1515
}
1616

17+
#[inline]
18+
pub(crate) fn strip_first_newline(s: &str) -> &str {
19+
if let Some(s) = s.strip_prefix("\r\n") {
20+
s
21+
} else if let Some(s) = s.strip_prefix('\n') {
22+
s
23+
} else {
24+
s
25+
}
26+
}
27+
1728
pub(crate) fn ends_with_empty_line(text: &str) -> bool {
1829
let s = text.trim_end_matches(whitespace_matcher);
1930
// also matches when text is just whitespaces

src/template.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -449,11 +449,8 @@ impl Template {
449449
if trim_start {
450450
RawString(s.trim_start().to_owned())
451451
} else if trim_start_line {
452-
RawString(
453-
s.trim_start_matches(grammar::whitespace_matcher)
454-
.trim_start_matches(grammar::newline_matcher)
455-
.to_owned(),
456-
)
452+
let s = s.trim_start_matches(grammar::whitespace_matcher);
453+
RawString(grammar::strip_first_newline(s).to_owned())
457454
} else {
458455
RawString(s)
459456
}

tests/helper_with_space.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,34 @@ fn test_helper_with_space_param() {
3434
.unwrap();
3535
assert_eq!(s, "Output: Mozilla Firefox, Google Chrome".to_owned());
3636
}
37+
38+
#[test]
39+
fn test_empty_lines_472() {
40+
let mut r = Handlebars::new();
41+
42+
r.register_template_string(
43+
"t1",
44+
r#"{{#each routes}}
45+
import { default as {{this.handler}} } from '{{this.file_path}}'
46+
{{/each}}
47+
48+
addEventListener('fetch', (event) => {
49+
event.respondWith(handleEvent(event))
50+
})"#,
51+
)
52+
.unwrap();
53+
54+
let data = json!({"routes": [{"handler": "__hello_handler", "file_path": "./hello.js"},
55+
{"handler": "__world_index_handler", "file_path": "./world/index.js"},
56+
{"handler": "__index_handler", "file_path": "./index.js"}]});
57+
58+
let exp = r#"import { default as __hello_handler } from './hello.js'
59+
import { default as __world_index_handler } from './world/index.js'
60+
import { default as __index_handler } from './index.js'
61+
62+
addEventListener('fetch', (event) => {
63+
event.respondWith(handleEvent(event))
64+
})"#;
65+
66+
assert_eq!(r.render("t1", &data).unwrap(), exp);
67+
}

0 commit comments

Comments
 (0)