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

parser: add optional {% endwhen %} #165

Merged
merged 3 commits into from
Sep 10, 2024
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
18 changes: 18 additions & 0 deletions book/src/template_syntax.md
Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,24 @@ You can also match against multiple alternative patterns at once:
{% endmatch %}
```

For better interoperability with linters and auto-formatters like [djLint],
you can also use a optional `{% endwhen %}` node to close a `{% when %}` case:

```jinja
{% match number %}
{% when 0 | 2 | 4 | 6 | 8 %}
even
{% endwhen %}
{% when 1 | 3 | 5 | 7 | 9 %}
odd
{% endwhen %}
{% else }
unknown
{% endmatch %}
```

[djLint]: <https://github.com/djlint/djlint>

### Referencing and dereferencing variables

If you need to put something behind a reference or to dereference it, you
Expand Down
41 changes: 36 additions & 5 deletions rinja_parser/src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ pub struct When<'a> {
}

impl<'a> When<'a> {
fn r#match(i: &'a str, s: &State<'_>) -> ParseResult<'a, WithSpan<'a, Self>> {
fn r#else(i: &'a str, s: &State<'_>) -> ParseResult<'a, WithSpan<'a, Self>> {
let start = i;
let mut p = tuple((
|i| s.tag_block_start(i),
Expand Down Expand Up @@ -204,6 +204,33 @@ impl<'a> When<'a> {
#[allow(clippy::self_named_constructors)]
fn when(i: &'a str, s: &State<'_>) -> ParseResult<'a, WithSpan<'a, Self>> {
let start = i;
let endwhen = map(
consumed(ws(pair(
delimited(
|i| s.tag_block_start(i),
opt(Whitespace::parse),
ws(keyword("endwhen")),
),
cut(tuple((
opt(Whitespace::parse),
|i| s.tag_block_end(i),
many0(value((), ws(|i| Comment::parse(i, s)))),
))),
))),
|(span, (pws, _))| {
// A comment node is used to pass the whitespace suppressing information to the
// generator. This way we don't have to fix up the next `when` node or the closing
// `endmatch`. Any whitespaces after `endwhen` are to be suppressed. Actually, they
// don't wind up in the AST anyway.
Node::Comment(WithSpan::new(
Comment {
ws: Ws(pws, Some(Whitespace::Suppress)),
content: "",
},
span,
))
},
);
let mut p = tuple((
|i| s.tag_block_start(i),
opt(Whitespace::parse),
Expand All @@ -213,9 +240,13 @@ impl<'a> When<'a> {
opt(Whitespace::parse),
|i| s.tag_block_end(i),
cut(|i| Node::many(i, s)),
opt(endwhen),
))),
));
let (i, (_, pws, _, (target, nws, _, nodes))) = p(i)?;
let (i, (_, pws, _, (target, nws, _, mut nodes, endwhen))) = p(i)?;
if let Some(endwhen) = endwhen {
nodes.push(endwhen);
}
Ok((
i,
WithSpan::new(
Expand Down Expand Up @@ -658,15 +689,15 @@ impl<'a> Match<'a> {
cut(tuple((
ws(many0(ws(value((), |i| Comment::parse(i, s))))),
many0(|i| When::when(i, s)),
cut(tuple((
opt(|i| When::r#match(i, s)),
cut(pair(
opt(|i| When::r#else(i, s)),
cut(tuple((
ws(|i| check_block_start(i, start, s, "match", "endmatch")),
opt(Whitespace::parse),
end_node("match", "endmatch"),
opt(Whitespace::parse),
))),
))),
)),
))),
))),
));
Expand Down
35 changes: 35 additions & 0 deletions testing/tests/matches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,3 +265,38 @@ fn test_match_with_patterns() {
let s = MatchPatterns { n: 12 };
assert_eq!(s.render().unwrap(), "12");
}

#[derive(Template)]
#[template(in_doc = true, ext = "html")]
/// ```rinja
/// {% match result %}
/// {% when Some(Ok(s)) -%}
/// good: {{s}}
/// {%- endwhen +%}
/// {# This is not good: #}
/// {%+ when Some(Err(s)) -%}
/// bad: {{s}}
/// {%- endwhen +%}
/// {%+ else -%}
/// unprocessed
/// {% endmatch %}
/// ```
struct EndWhen<'a> {
result: Option<Result<&'a str, &'a str>>,
}

#[test]
fn test_end_when() {
let tmpl = EndWhen {
result: Some(Ok("msg")),
};
assert_eq!(tmpl.to_string(), "good: msg");

let tmpl = EndWhen {
result: Some(Err("msg")),
};
assert_eq!(tmpl.to_string(), "bad: msg");

let tmpl = EndWhen { result: None };
assert_eq!(tmpl.to_string(), "unprocessed\n");
}