Dataset Viewer
Auto-converted to Parquet Duplicate
repo
string
pull_number
int64
instance_id
string
issue_numbers
sequence
base_commit
string
patch
string
test_patch
string
problem_statement
string
hints_text
string
created_at
string
version
string
updated_at
string
environment_setup_commit
string
FAIL_TO_PASS
sequence
PASS_TO_PASS
sequence
FAIL_TO_FAIL
sequence
PASS_TO_FAIL
sequence
source_dir
string
rinja-rs/askama
673
rinja-rs__askama-673
[ "671" ]
358f7cd07dc42ba4189d2661461ff0b43a27c304
diff --git a/askama_shared/src/generator.rs b/askama_shared/src/generator.rs --- a/askama_shared/src/generator.rs +++ b/askama_shared/src/generator.rs @@ -246,7 +246,7 @@ struct Generator<'a, S: std::hash::BuildHasher> { next_ws: Option<&'a str>, // Whitespace suppression from the previous non-literal. Will be used to // determine whether to flush prefix whitespace from the next literal. - skip_ws: bool, + skip_ws: WhitespaceHandling, // If currently in a block, this will contain the name of a potential parent block super_block: Option<(&'a str, usize)>, // buffer for writable diff --git a/askama_shared/src/generator.rs b/askama_shared/src/generator.rs --- a/askama_shared/src/generator.rs +++ b/askama_shared/src/generator.rs @@ -272,7 +272,7 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { heritage, locals, next_ws: None, - skip_ws: false, + skip_ws: WhitespaceHandling::Preserve, super_block: None, buf_writable: vec![], named: 0, diff --git a/askama_shared/src/generator.rs b/askama_shared/src/generator.rs --- a/askama_shared/src/generator.rs +++ b/askama_shared/src/generator.rs @@ -1230,13 +1230,22 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { fn visit_lit(&mut self, lws: &'a str, val: &'a str, rws: &'a str) { assert!(self.next_ws.is_none()); if !lws.is_empty() { - if self.skip_ws { - self.skip_ws = false; - } else if val.is_empty() { - assert!(rws.is_empty()); - self.next_ws = Some(lws); - } else { - self.buf_writable.push(Writable::Lit(lws)); + match self.skip_ws { + WhitespaceHandling::Suppress => { + self.skip_ws = WhitespaceHandling::Preserve; + } + _ if val.is_empty() => { + assert!(rws.is_empty()); + self.next_ws = Some(lws); + } + WhitespaceHandling::Preserve => self.buf_writable.push(Writable::Lit(lws)), + WhitespaceHandling::Minimize => { + self.buf_writable + .push(Writable::Lit(match lws.contains('\n') { + true => "\n", + false => " ", + })) + } } } diff --git a/askama_shared/src/generator.rs b/askama_shared/src/generator.rs --- a/askama_shared/src/generator.rs +++ b/askama_shared/src/generator.rs @@ -1819,11 +1828,12 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { self.prepare_ws(ws); } - fn should_trim_ws(&self, ws: Option<Whitespace>) -> bool { + fn should_trim_ws(&self, ws: Option<Whitespace>) -> WhitespaceHandling { match ws { - Some(Whitespace::Trim) => true, - Some(Whitespace::Preserve) => false, - None => self.whitespace == WhitespaceHandling::Suppress, + Some(Whitespace::Suppress) => WhitespaceHandling::Suppress, + Some(Whitespace::Preserve) => WhitespaceHandling::Preserve, + Some(Whitespace::Minimize) => WhitespaceHandling::Minimize, + None => self.whitespace, } } diff --git a/askama_shared/src/generator.rs b/askama_shared/src/generator.rs --- a/askama_shared/src/generator.rs +++ b/askama_shared/src/generator.rs @@ -1837,11 +1847,24 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { // If `whitespace` is set to `suppress`, we keep the whitespace characters only if there is // a `+` character. - if !self.should_trim_ws(ws.0) { - let val = self.next_ws.unwrap(); - if !val.is_empty() { - self.buf_writable.push(Writable::Lit(val)); + match self.should_trim_ws(ws.0) { + WhitespaceHandling::Preserve => { + let val = self.next_ws.unwrap(); + if !val.is_empty() { + self.buf_writable.push(Writable::Lit(val)); + } + } + WhitespaceHandling::Minimize => { + let val = self.next_ws.unwrap(); + if !val.is_empty() { + self.buf_writable + .push(Writable::Lit(match val.contains('\n') { + true => "\n", + false => " ", + })); + } } + WhitespaceHandling::Suppress => {} } self.next_ws = None; } diff --git a/askama_shared/src/lib.rs b/askama_shared/src/lib.rs --- a/askama_shared/src/lib.rs +++ b/askama_shared/src/lib.rs @@ -314,6 +314,10 @@ pub(crate) enum WhitespaceHandling { Preserve, /// It'll remove all the whitespace characters before and after the jinja block. Suppress, + /// It'll remove all the whitespace characters except one before and after the jinja blocks. + /// If there is a newline character, the preserved character in the trimmed characters, it will + /// the one preserved. + Minimize, } impl Default for WhitespaceHandling { diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -132,14 +132,16 @@ pub(crate) enum Target<'a> { #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) enum Whitespace { Preserve, - Trim, + Suppress, + Minimize, } impl From<char> for Whitespace { fn from(c: char) -> Self { match c { '+' => Self::Preserve, - '-' => Self::Trim, + '-' => Self::Suppress, + '~' => Self::Minimize, _ => panic!("unsupported `Whitespace` conversion"), } } diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -677,7 +679,7 @@ expr_prec_layer!(expr_and, expr_compare, "&&"); expr_prec_layer!(expr_or, expr_and, "||"); fn expr_handle_ws(i: &str) -> IResult<&str, Whitespace> { - alt((char('-'), char('+')))(i).map(|(s, r)| (s, Whitespace::from(r))) + alt((char('-'), char('+'), char('~')))(i).map(|(s, r)| (s, Whitespace::from(r))) } fn expr_any(i: &str) -> IResult<&str, Expr<'_>> { diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -1135,9 +1137,11 @@ fn block_comment<'a>(i: &'a str, s: &State<'_>) -> IResult<&'a str, Node<'a>> { )); let (i, (_, (pws, tail, _))) = p(i)?; let nws = if tail.ends_with('-') { - Some(Whitespace::Trim) + Some(Whitespace::Suppress) } else if tail.ends_with('+') { Some(Whitespace::Preserve) + } else if tail.ends_with('~') { + Some(Whitespace::Minimize) } else { None }; diff --git a/book/src/configuration.md b/book/src/configuration.md --- a/book/src/configuration.md +++ b/book/src/configuration.md @@ -11,7 +11,7 @@ This example file demonstrates the default configuration: [general] # Directories to search for templates, relative to the crate root. dirs = ["templates"] -# Unless you add a `-` in a block, whitespace won't be trimmed. +# Unless you add a `-` in a block, whitespace characters won't be trimmed. whitespace = "preserve" ``` diff --git a/book/src/configuration.md b/book/src/configuration.md --- a/book/src/configuration.md +++ b/book/src/configuration.md @@ -24,7 +24,7 @@ whitespace should be suppressed before or after a block. For example: {%- if something %} Hello -(% endif %} +{% endif %} ``` In the template above, only the whitespace between `<div>` and `{%-` will be diff --git a/book/src/configuration.md b/book/src/configuration.md --- a/book/src/configuration.md +++ b/book/src/configuration.md @@ -35,11 +35,26 @@ characters, you can use the `+` operator: ```jinja {% if something +%} Hello -(%+ endif %} +{%+ endif %} ``` In this example, `Hello` will be surrounded with newline characters. +There is a third possibility: in case you want to suppress all whitespace +characters except one, you can use `~`: + +```jinja +{% if something ~%} +Hello +{%~ endif %} +``` + +To be noted, if one of the trimmed characters is a newline, then the only +character remaining will be a newline. + +If you want this to be the default behaviour, you can set `whitespace` to +`"minimize"`. + Here is an example that defines two custom syntaxes: ```toml
diff --git a/askama_shared/src/lib.rs b/askama_shared/src/lib.rs --- a/askama_shared/src/lib.rs +++ b/askama_shared/src/lib.rs @@ -701,5 +705,14 @@ mod tests { ) .unwrap(); assert_eq!(config.whitespace, WhitespaceHandling::Preserve); + + let config = Config::new( + r#" + [general] + whitespace = "minimize" + "#, + ) + .unwrap(); + assert_eq!(config.whitespace, WhitespaceHandling::Minimize); } } diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -1443,12 +1447,12 @@ mod tests { #[test] fn change_delimiters_parse_filter() { let syntax = Syntax { - expr_start: "{~", - expr_end: "~}", + expr_start: "{=", + expr_end: "=}", ..Syntax::default() }; - super::parse("{~ strvar|e ~}", &syntax).unwrap(); + super::parse("{= strvar|e =}", &syntax).unwrap(); } #[test] diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -1665,31 +1669,31 @@ mod tests { ); assert_eq!( super::parse("{#- #}", s).unwrap(), - vec![Node::Comment(Ws(Some(Whitespace::Trim), None))], + vec![Node::Comment(Ws(Some(Whitespace::Suppress), None))], ); assert_eq!( super::parse("{# -#}", s).unwrap(), - vec![Node::Comment(Ws(None, Some(Whitespace::Trim)))], + vec![Node::Comment(Ws(None, Some(Whitespace::Suppress)))], ); assert_eq!( super::parse("{#--#}", s).unwrap(), vec![Node::Comment(Ws( - Some(Whitespace::Trim), - Some(Whitespace::Trim) + Some(Whitespace::Suppress), + Some(Whitespace::Suppress) ))], ); assert_eq!( super::parse("{#- foo\n bar -#}", s).unwrap(), vec![Node::Comment(Ws( - Some(Whitespace::Trim), - Some(Whitespace::Trim) + Some(Whitespace::Suppress), + Some(Whitespace::Suppress) ))], ); assert_eq!( super::parse("{#- foo\n {#- bar\n -#} baz -#}", s).unwrap(), vec![Node::Comment(Ws( - Some(Whitespace::Trim), - Some(Whitespace::Trim) + Some(Whitespace::Suppress), + Some(Whitespace::Suppress) ))], ); assert_eq!( diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -1721,6 +1725,35 @@ mod tests { Some(Whitespace::Preserve) ))], ); + assert_eq!( + super::parse("{#~ #}", s).unwrap(), + vec![Node::Comment(Ws(Some(Whitespace::Minimize), None))], + ); + assert_eq!( + super::parse("{# ~#}", s).unwrap(), + vec![Node::Comment(Ws(None, Some(Whitespace::Minimize)))], + ); + assert_eq!( + super::parse("{#~~#}", s).unwrap(), + vec![Node::Comment(Ws( + Some(Whitespace::Minimize), + Some(Whitespace::Minimize) + ))], + ); + assert_eq!( + super::parse("{#~ foo\n bar ~#}", s).unwrap(), + vec![Node::Comment(Ws( + Some(Whitespace::Minimize), + Some(Whitespace::Minimize) + ))], + ); + assert_eq!( + super::parse("{#~ foo\n {#~ bar\n ~#} baz -~#}", s).unwrap(), + vec![Node::Comment(Ws( + Some(Whitespace::Minimize), + Some(Whitespace::Minimize) + ))], + ); assert_eq!( super::parse("{# foo {# bar #} {# {# baz #} qux #} #}", s).unwrap(), diff --git /dev/null b/testing/test_minimize.toml new file mode 100644 --- /dev/null +++ b/testing/test_minimize.toml @@ -0,0 +1,2 @@ +[general] +whitespace = "minimize" diff --git a/testing/tests/whitespace.rs b/testing/tests/whitespace.rs --- a/testing/tests/whitespace.rs +++ b/testing/tests/whitespace.rs @@ -41,3 +41,46 @@ fn test_extra_whitespace() { template.nested_1.nested_2.hash.insert("key", "value"); assert_eq!(template.render().unwrap(), "\n0\n0\n0\n0\n\n\n\n0\n0\n0\n0\n0\n\na0\na1\nvalue\n\n\n\n\n\n[\n &quot;a0&quot;,\n &quot;a1&quot;,\n &quot;a2&quot;,\n &quot;a3&quot;\n]\n[\n &quot;a0&quot;,\n &quot;a1&quot;,\n &quot;a2&quot;,\n &quot;a3&quot;\n][\n &quot;a0&quot;,\n &quot;a1&quot;,\n &quot;a2&quot;,\n &quot;a3&quot;\n]\n[\n &quot;a1&quot;\n][\n &quot;a1&quot;\n]\n[\n &quot;a1&quot;,\n &quot;a2&quot;\n][\n &quot;a1&quot;,\n &quot;a2&quot;\n]\n[\n &quot;a1&quot;\n][\n &quot;a1&quot;\n]1-1-1\n3333 3\n2222 2\n0000 0\n3333 3\n\ntruefalse\nfalsefalsefalse\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); } + +macro_rules! test_template_minimize { + ($source:literal, $rendered:expr) => {{ + #[derive(Template)] + #[template(source = $source, ext = "txt", config = "test_minimize.toml")] + struct CondWs; + + assert_eq!(CondWs.render().unwrap(), $rendered); + }}; +} + +macro_rules! test_template { + ($source:literal, $rendered:expr) => {{ + #[derive(Template)] + #[template(source = $source, ext = "txt")] + struct CondWs; + + assert_eq!(CondWs.render().unwrap(), $rendered); + }}; +} + +#[test] +fn test_minimize_whitespace() { + test_template_minimize!( + "\n1\r\n{% if true %}\n\n2\r\n\r\n{% endif %} 3\r\n\r\n\r\n", + "\n1\n\n2\n 3" + ); + test_template_minimize!( + "\n1\r\n{%+ if true %}\n\n2\r\n\r\n{% endif %} 3\r\n\r\n\r\n", + "\n1\r\n\n2\n 3" + ); + test_template_minimize!( + "\n1\r\n{%- if true %}\n\n2\r\n\r\n{% endif %} 3\r\n\r\n\r\n", + "\n1\n2\n 3" + ); + test_template_minimize!(" \n1 \n{% if true %} 2 {% endif %}3 ", " \n1\n 2 3"); + + test_template!( + "\n1\r\n{%~ if true ~%}\n\n2\r\n\r\n{%~ endif ~%} 3\r\n\r\n\r\n", + "\n1\n\n2\n 3" + ); + test_template!(" \n1 \n{%~ if true ~%} 2 {%~ endif ~%}3 ", " \n1\n 2 3"); +}
Trim all but 1 whitespace jinja condition @vallentin suggested [here](https://github.com/djc/askama/pull/664#pullrequestreview-945253861) that we could extend the "trim_all_whitespace" feature to be able to trim all whitespace characters but one. So currently, we have: ```jinja <div> {%- if foo -%} blabla {%- endif -%} </div> ``` Which will remove all whitespace characters before and after (by using `-`) and we have: ```jinja <div> {%+ if foo +%} blabla {%+ endif +%} </div> ``` Which means that the whitespace should be saved (only useful when the "trim all whitespace" feature is enabled). The idea would now to add a new character to strip all whitespace characters but one. I propose `~`: ```jinja <div> {%~ if foo %} blabla {% endif %} </div> ```
I'm on board with all that, including the proposed operator. Ok, then I'll make a PR soon. :) I like that! For readability I'd like it best if a run of whitespaces becomes a single '\n' if it contains an '\n', or a space otherwise. I'm fine with implementing it this way. Anyone else has an opinion maybe? Yeah, I think that approach makes sense. I'd love, if it is also configurable like #664. So you can configure it through the config file or part of the `#[template(...)]`. As minifying HTML is part of my rendering pipeline, so if it was possible to enable it globally, without needing to sprinkle `~` everywhere, then that would be lovely :) Sure. What should we name the config parameter then? Also, if both "trim_all" and "trim_all_but_one" are enabled, what should we do? Maybe instead of having them be individual. Maybe it might be possible to do `whitespace = "trim_all"` and `whitespace = "trim_all_but_one"` Maybe @djc was right: I should have gone with a string argument for "trim_whitespace" so then we wouldn't have this problem. EDIT: @vallentin Ah we reached the same conclusion haha. > Maybe @djc was right: I should have gone with a string argument for "trim_whitespace" so then we wouldn't have this problem. Yup! Ok, then I'll change the parameter as well. :) > Maybe @djc was right: I should have gone with a string argument for "trim_whitespace" so then we wouldn't have this problem. > > @vallentin Ah we reached the same conclusion haha. Well, there hasn't been a new release yet. So it's not to late to play with it :) I think the names should be `suppress`, `preserve`, and then maybe `minimize`? I think a mix between @djc's and @vallentin's propositions would work better. What do you think of: ``` trim_whitespace = "all" | "all_but_one" | "preserve" ``` ? I still dislike anything "trim" because that's not, conceptually, what it is. We're either suppressing the whitespace from the template or preserving it, and this option is somewhere in between. To my eyes, `all_but_one` seems pretty ugly, and it kind of begs the question about which one. I do like the idea of just calling it `whitespace` by default, to keep things simple and concise. That makes sense. Then let's go with `whitespace` and `suppress`|`preserve`|`minimize`.
2022-04-21T14:51:49Z
0.11
2022-04-26T08:31:21Z
7b6f1df433a7f11612608644342b898cd6be8ff5
[ "filters::json::tests::test_json", "filters::tests::test_abs", "filters::tests::test_center", "filters::tests::test_capitalize", "filters::tests::test_filesizeformat", "filters::tests::test_indent", "filters::tests::test_into_f64", "filters::tests::test_into_isize", "filters::tests::test_join", "f...
[]
[]
[]
auto_2025-06-03
rinja-rs/askama
652
rinja-rs__askama-652
[ "651" ]
b14982f97ffd20039286171d56e6fcfab21f56bc
diff --git a/askama_shared/src/filters/mod.rs b/askama_shared/src/filters/mod.rs --- a/askama_shared/src/filters/mod.rs +++ b/askama_shared/src/filters/mod.rs @@ -330,20 +330,14 @@ where /// Capitalize a value. The first character will be uppercase, all others lowercase. pub fn capitalize<T: fmt::Display>(s: T) -> Result<String> { - let mut s = s.to_string(); - - match s.get_mut(0..1).map(|s| { - s.make_ascii_uppercase(); - &*s - }) { - None => Ok(s), - _ => { - s.get_mut(1..).map(|s| { - s.make_ascii_lowercase(); - &*s - }); - Ok(s) + let s = s.to_string(); + match s.chars().next() { + Some(c) => { + let mut replacement: String = c.to_uppercase().collect(); + replacement.push_str(&s[c.len_utf8()..].to_lowercase()); + Ok(replacement) } + _ => Ok(s), } }
diff --git a/askama_shared/src/filters/mod.rs b/askama_shared/src/filters/mod.rs --- a/askama_shared/src/filters/mod.rs +++ b/askama_shared/src/filters/mod.rs @@ -655,6 +649,9 @@ mod tests { assert_eq!(capitalize(&"").unwrap(), "".to_string()); assert_eq!(capitalize(&"FoO").unwrap(), "Foo".to_string()); assert_eq!(capitalize(&"foO BAR").unwrap(), "Foo bar".to_string()); + assert_eq!(capitalize(&"äØÄÅÖ").unwrap(), "Äøäåö".to_string()); + assert_eq!(capitalize(&"ß").unwrap(), "SS".to_string()); + assert_eq!(capitalize(&"ßß").unwrap(), "SSß".to_string()); } #[test]
Capitalize does not work with non ascii chars Capitalize filter only works with ascii chars not chars like å, ä and ö.
This custom filter does what i expected capitalize to do. ```rust mod filters { pub fn cap(s: &str) -> ::askama::Result<String> { match s.chars().next() { Some(c) => { if c.is_lowercase() { let mut replacement: String = c.to_uppercase().collect(); replacement.push_str(&s[c.len_utf8()..]); Ok(replacement) } else { Ok(s.to_string()) } } _ => Ok(s.to_string()) } } } ``` Thanks for the report, want to submit a PR? Ideally including a basic test would be great, too!
2022-03-26T15:32:24Z
0.11
2022-03-26T17:50:42Z
7b6f1df433a7f11612608644342b898cd6be8ff5
[ "filters::tests::test_capitalize" ]
[ "filters::tests::test_abs", "filters::tests::test_center", "filters::tests::test_filesizeformat", "filters::json::tests::test_json", "filters::tests::test_indent", "filters::tests::test_into_f64", "filters::tests::test_into_isize", "filters::tests::test_join", "filters::tests::test_linebreaks", "f...
[ "filters::yaml::tests::test_yaml" ]
[]
auto_2025-06-03
rinja-rs/askama
359
rinja-rs__askama-359
[ "357" ]
17b9d06814cee84bfd57b73e1941b63187ec5f65
diff --git a/askama_shared/src/filters/mod.rs b/askama_shared/src/filters/mod.rs --- a/askama_shared/src/filters/mod.rs +++ b/askama_shared/src/filters/mod.rs @@ -249,7 +249,7 @@ pub fn indent(s: &dyn fmt::Display, width: &usize) -> Result<String> { #[cfg(feature = "num-traits")] /// Casts number to f64 -pub fn into_f64<T>(number: T) -> Result<f64> +pub fn into_f64<T>(number: &T) -> Result<f64> where T: NumCast, { diff --git a/askama_shared/src/filters/mod.rs b/askama_shared/src/filters/mod.rs --- a/askama_shared/src/filters/mod.rs +++ b/askama_shared/src/filters/mod.rs @@ -258,7 +258,7 @@ where #[cfg(feature = "num-traits")] /// Casts number to isize -pub fn into_isize<T>(number: T) -> Result<isize> +pub fn into_isize<T>(number: &T) -> Result<isize> where T: NumCast, {
diff --git a/askama_shared/src/filters/mod.rs b/askama_shared/src/filters/mod.rs --- a/askama_shared/src/filters/mod.rs +++ b/askama_shared/src/filters/mod.rs @@ -460,22 +460,22 @@ mod tests { #[test] #[allow(clippy::float_cmp)] fn test_into_f64() { - assert_eq!(into_f64(1).unwrap(), 1.0 as f64); - assert_eq!(into_f64(1.9).unwrap(), 1.9 as f64); - assert_eq!(into_f64(-1.9).unwrap(), -1.9 as f64); - assert_eq!(into_f64(INFINITY as f32).unwrap(), INFINITY); - assert_eq!(into_f64(-INFINITY as f32).unwrap(), -INFINITY); + assert_eq!(into_f64(&1).unwrap(), 1.0 as f64); + assert_eq!(into_f64(&1.9).unwrap(), 1.9 as f64); + assert_eq!(into_f64(&-1.9).unwrap(), -1.9 as f64); + assert_eq!(into_f64(&(INFINITY as f32)).unwrap(), INFINITY); + assert_eq!(into_f64(&(-INFINITY as f32)).unwrap(), -INFINITY); } #[cfg(feature = "num-traits")] #[test] fn test_into_isize() { - assert_eq!(into_isize(1).unwrap(), 1 as isize); - assert_eq!(into_isize(1.9).unwrap(), 1 as isize); - assert_eq!(into_isize(-1.9).unwrap(), -1 as isize); - assert_eq!(into_isize(1.5 as f64).unwrap(), 1 as isize); - assert_eq!(into_isize(-1.5 as f64).unwrap(), -1 as isize); - match into_isize(INFINITY) { + assert_eq!(into_isize(&1).unwrap(), 1 as isize); + assert_eq!(into_isize(&1.9).unwrap(), 1 as isize); + assert_eq!(into_isize(&-1.9).unwrap(), -1 as isize); + assert_eq!(into_isize(&(1.5 as f64)).unwrap(), 1 as isize); + assert_eq!(into_isize(&(-1.5 as f64)).unwrap(), -1 as isize); + match into_isize(&INFINITY) { Err(Fmt(fmt::Error)) => {} _ => panic!("Should return error of type Err(Fmt(fmt::Error))"), }; diff --git a/testing/tests/filters.rs b/testing/tests/filters.rs --- a/testing/tests/filters.rs +++ b/testing/tests/filters.rs @@ -50,6 +50,20 @@ fn filter_fmt() { assert_eq!(t.render().unwrap(), "\"formatted\""); } +#[derive(Template)] +#[template( + source = "{{ 1|into_f64 }} {{ 1.9|into_isize }}", + ext = "txt", + escape = "none" +)] +struct IntoNumbersTemplate; + +#[test] +fn into_numbers_fmt() { + let t = IntoNumbersTemplate; + assert_eq!(t.render().unwrap(), "1 1"); +} + #[derive(Template)] #[template(source = "{{ s|myfilter }}", ext = "txt")] struct MyFilterTemplate<'a> {
into_f64, into_isize unusable `{{ number | into_f64 }}` expands to `into_f64(&number)`, which doesn't compile, because borrowed number doesn't `impl NumCast`.
Thanks for the report. Would you mind submitting a patch that adds the appropriate `*` operators? Maybe it's better to have info_f64 take `&T`? That's fine, too! Whatever works in the context of Askama filters.
2020-09-16T01:05:50Z
0.10
2020-09-16T09:49:22Z
49252d2457f280026c020d0df46733578eb959a5
[ "filters::tests::test_abs", "filters::tests::test_filesizeformat", "filters::tests::test_center", "filters::tests::test_capitalize", "filters::json::tests::test_json", "filters::tests::test_into_f64", "filters::tests::test_indent", "filters::tests::test_into_isize", "filters::tests::test_lower", "...
[]
[]
[]
auto_2025-06-03
rinja-rs/askama
304
rinja-rs__askama-304
[ "285", "196" ]
cff49453a851029f87b35512f5234a999fea3e6c
diff --git a/askama_shared/src/generator.rs b/askama_shared/src/generator.rs --- a/askama_shared/src/generator.rs +++ b/askama_shared/src/generator.rs @@ -909,7 +909,9 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { Expr::StrLit(s) => self.visit_str_lit(buf, s), Expr::CharLit(s) => self.visit_char_lit(buf, s), Expr::Var(s) => self.visit_var(buf, s), + Expr::VarCall(var, ref args) => self.visit_var_call(buf, var, args), Expr::Path(ref path) => self.visit_path(buf, path), + Expr::PathCall(ref path, ref args) => self.visit_path_call(buf, path, args), Expr::Array(ref elements) => self.visit_array(buf, elements), Expr::Attr(ref obj, name) => self.visit_attr(buf, obj, name), Expr::Index(ref obj, ref key) => self.visit_index(buf, obj, key), diff --git a/askama_shared/src/generator.rs b/askama_shared/src/generator.rs --- a/askama_shared/src/generator.rs +++ b/askama_shared/src/generator.rs @@ -1028,7 +1030,10 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { } let scoped = match *arg { - Expr::Filter(_, _) | Expr::MethodCall(_, _, _) => true, + Expr::Filter(_, _) + | Expr::MethodCall(_, _, _) + | Expr::VarCall(_, _) + | Expr::PathCall(_, _) => true, _ => false, }; diff --git a/askama_shared/src/generator.rs b/askama_shared/src/generator.rs --- a/askama_shared/src/generator.rs +++ b/askama_shared/src/generator.rs @@ -1160,6 +1165,19 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { DisplayWrap::Unwrapped } + fn visit_path_call(&mut self, buf: &mut Buffer, path: &[&str], args: &[Expr]) -> DisplayWrap { + for (i, part) in path.iter().enumerate() { + if i > 0 { + buf.write("::"); + } + buf.write(part); + } + buf.write("(&"); + self._visit_args(buf, args); + buf.write(")"); + DisplayWrap::Unwrapped + } + fn visit_var(&mut self, buf: &mut Buffer, s: &str) -> DisplayWrap { if self.locals.contains(s) || s == "self" { buf.write(s); diff --git a/askama_shared/src/generator.rs b/askama_shared/src/generator.rs --- a/askama_shared/src/generator.rs +++ b/askama_shared/src/generator.rs @@ -1170,6 +1188,20 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { DisplayWrap::Unwrapped } + fn visit_var_call(&mut self, buf: &mut Buffer, s: &str, args: &[Expr]) -> DisplayWrap { + buf.write("("); + if self.locals.contains(s) || s == "self" { + buf.write(s); + } else { + buf.write("self."); + buf.write(s); + } + buf.write(")(&"); + self._visit_args(buf, args); + buf.write(")"); + DisplayWrap::Unwrapped + } + fn visit_bool_lit(&mut self, buf: &mut Buffer, s: &str) -> DisplayWrap { buf.write(s); DisplayWrap::Unwrapped diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -10,14 +10,16 @@ use std::str; use crate::Syntax; -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub enum Expr<'a> { BoolLit(&'a str), NumLit(&'a str), StrLit(&'a str), CharLit(&'a str), Var(&'a str), + VarCall(&'a str, Vec<Expr<'a>>), Path(Vec<&'a str>), + PathCall(Vec<&'a str>, Vec<Expr<'a>>), Array(Vec<Expr<'a>>), Attr(Box<Expr<'a>>, &'a str), Index(Box<Expr<'a>>, Box<Expr<'a>>), diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -30,7 +32,7 @@ pub enum Expr<'a> { RustMacro(&'a str, &'a str), } -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub enum MatchVariant<'a> { Path(Vec<&'a str>), Name(&'a str), diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -39,7 +41,7 @@ pub enum MatchVariant<'a> { CharLit(&'a str), } -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub enum MatchParameter<'a> { Name(&'a str), NumLit(&'a str), diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -47,16 +49,16 @@ pub enum MatchParameter<'a> { CharLit(&'a str), } -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub enum Target<'a> { Name(&'a str), Tuple(Vec<&'a str>), } -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq)] pub struct WS(pub bool, pub bool); -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub struct Macro<'a> { pub ws1: WS, pub args: Vec<&'a str>, diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -64,7 +66,7 @@ pub struct Macro<'a> { pub ws2: WS, } -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub enum Node<'a> { Lit(&'a str, &'a str, &'a str), Comment(WS), diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -84,6 +86,7 @@ pub enum Node<'a> { } pub type Cond<'a> = (WS, Option<Expr<'a>>, Vec<Node<'a>>); + pub type When<'a> = ( WS, Option<MatchVariant<'a>>, diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -91,7 +94,7 @@ pub type When<'a> = ( Vec<Node<'a>>, ); -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub enum MatchParameters<'a> { Simple(Vec<MatchParameter<'a>>), Named(Vec<(&'a str, Option<MatchParameter<'a>>)>), diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -301,15 +304,30 @@ fn expr_var(i: &[u8]) -> IResult<&[u8], Expr> { map(identifier, |s| Expr::Var(s))(i) } -fn expr_path(i: &[u8]) -> IResult<&[u8], Expr> { +fn expr_var_call(i: &[u8]) -> IResult<&[u8], Expr> { + let (i, (s, args)) = tuple((identifier, arguments))(i)?; + Ok((i, Expr::VarCall(s, args))) +} + +fn path(i: &[u8]) -> IResult<&[u8], Vec<&str>> { let tail = separated_nonempty_list(tag("::"), identifier); let (i, (start, _, rest)) = tuple((identifier, tag("::"), tail))(i)?; let mut path = vec![start]; path.extend(rest); + Ok((i, path)) +} + +fn expr_path(i: &[u8]) -> IResult<&[u8], Expr> { + let (i, path) = path(i)?; Ok((i, Expr::Path(path))) } +fn expr_path_call(i: &[u8]) -> IResult<&[u8], Expr> { + let (i, (path, args)) = tuple((path, arguments))(i)?; + Ok((i, Expr::PathCall(path, args))) +} + fn variant_path(i: &[u8]) -> IResult<&[u8], MatchVariant> { map(separated_nonempty_list(tag("::"), identifier), |path| { MatchVariant::Path(path) diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -437,9 +455,11 @@ fn expr_single(i: &[u8]) -> IResult<&[u8], Expr> { expr_num_lit, expr_str_lit, expr_char_lit, + expr_path_call, expr_path, expr_rust_macro, expr_array_lit, + expr_var_call, expr_var, expr_group, ))(i)
diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -1078,6 +1098,34 @@ mod tests { super::parse("{{ strvar|e }}", &Syntax::default()); } + #[test] + fn test_parse_var_call() { + assert_eq!( + super::parse("{{ function(\"123\", 3) }}", &Syntax::default()), + vec![super::Node::Expr( + super::WS(false, false), + super::Expr::VarCall( + "function", + vec![super::Expr::StrLit("123"), super::Expr::NumLit("3")] + ), + )], + ); + } + + #[test] + fn test_parse_path_call() { + assert_eq!( + super::parse("{{ self::function(\"123\", 3) }}", &Syntax::default()), + vec![super::Node::Expr( + super::WS(false, false), + super::Expr::PathCall( + vec!["self", "function"], + vec![super::Expr::StrLit("123"), super::Expr::NumLit("3")], + ), + )], + ); + } + #[test] fn change_delimiters_parse_filter() { let syntax = Syntax { diff --git a/testing/tests/simple.rs b/testing/tests/simple.rs --- a/testing/tests/simple.rs +++ b/testing/tests/simple.rs @@ -262,6 +262,45 @@ fn test_slice_literal() { assert_eq!(t.render().unwrap(), "a"); } +#[derive(Template)] +#[template(source = "Hello, {{ world(\"123\", 4) }}!", ext = "txt")] +struct FunctionRefTemplate { + world: fn(s: &str, v: &u8) -> String, +} + +#[test] +fn test_func_ref_call() { + let t = FunctionRefTemplate { + world: |s, r| format!("world({}, {})", s, r), + }; + assert_eq!(t.render().unwrap(), "Hello, world(123, 4)!"); +} + +#[allow(clippy::trivially_copy_pass_by_ref)] +fn world2(s: &str, v: &u8) -> String { + format!("world{}{}", v, s) +} + +#[derive(Template)] +#[template(source = "Hello, {{ self::world2(\"123\", 4) }}!", ext = "txt")] +struct PathFunctionTemplate; + +#[test] +fn test_path_func_call() { + assert_eq!(PathFunctionTemplate.render().unwrap(), "Hello, world4123!"); +} + +#[derive(Template)] +#[template(source = "Hello, {{ Self::world3(self, \"123\", 4) }}!", ext = "txt")] +struct FunctionTemplate; + +impl FunctionTemplate { + #[allow(clippy::trivially_copy_pass_by_ref)] + fn world3(&self, s: &str, v: &u8) -> String { + format!("world{}{}", s, v) + } +} + #[derive(Template)] #[template(source = " {# foo -#} ", ext = "txt")] struct CommentTemplate {}
Call methods on root context Is there a syntax for calling methods implemented directly on the 'context'? A bare `function()` doesn't appear to do the trick Static method call Can I use static method in the template?
I think you can call `self.function()`? Documentation patches welcome. 😊 Can you give a concrete example? Presumably you have tried it? I tried like so: `{% let a = crate::a() %} ` Did you get an error? What was the error? Did you look at the generated code? The print attribute is "all", but it shows only `message: unable to parse template:` I think bare function calls are not supported at all. Might be a nice addition. Just add a variant `Expr::Call()` similar to `Expr::MethodCall()` and a parser called `expr_call` which is referenced in `expr_single` (before `expr_path`, and you can probably steal code from `expr_path`, too). (For bonus points, I think you can remove the `expr_var` parser by changing the `many1` in `expr_path` to `many0` to clean things up a little -- in a separate commit please.) As I fix it, it seems to affect existing rules, so I will not fix it. Really? I think we should fix it anyway. I'm going to try to take this on this week
2020-03-15T11:07:43Z
0.9
2020-03-18T21:33:57Z
cff49453a851029f87b35512f5234a999fea3e6c
[ "filters::tests::test_capitalize", "filters::tests::test_center", "filters::tests::test_filesizeformat", "filters::json::tests::test_json", "filters::tests::test_indent", "filters::tests::test_linebreaks", "filters::tests::test_linebreaksbr", "filters::tests::test_join", "filters::tests::test_lower"...
[]
[]
[]
auto_2025-06-03
rinja-rs/askama
861
rinja-rs__askama-861
[ "860" ]
43e92aa3b6b9cd967a70bd0fd54d1f087d6ed76b
diff --git a/askama_parser/src/expr.rs b/askama_parser/src/expr.rs --- a/askama_parser/src/expr.rs +++ b/askama_parser/src/expr.rs @@ -248,15 +248,15 @@ impl<'a> Suffix<'a> { } fn r#macro(i: &'a str) -> IResult<&'a str, Self> { - fn nested_parenthesis(i: &str) -> IResult<&str, ()> { + fn nested_parenthesis(input: &str) -> IResult<&str, ()> { let mut nested = 0; let mut last = 0; let mut in_str = false; let mut escaped = false; - for (i, b) in i.chars().enumerate() { - if !(b == '(' || b == ')') || !in_str { - match b { + for (i, c) in input.char_indices() { + if !(c == '(' || c == ')') || !in_str { + match c { '(' => nested += 1, ')' => { if nested == 0 { diff --git a/askama_parser/src/expr.rs b/askama_parser/src/expr.rs --- a/askama_parser/src/expr.rs +++ b/askama_parser/src/expr.rs @@ -281,16 +281,16 @@ impl<'a> Suffix<'a> { } } - if escaped && b != '\\' { + if escaped && c != '\\' { escaped = false; } } if nested == 0 { - Ok((&i[last..], ())) + Ok((&input[last..], ())) } else { Err(nom::Err::Error(error_position!( - i, + input, ErrorKind::SeparatedNonEmptyList ))) }
diff --git a/askama_parser/src/tests.rs b/askama_parser/src/tests.rs --- a/askama_parser/src/tests.rs +++ b/askama_parser/src/tests.rs @@ -788,3 +788,10 @@ fn test_parse_array() { )], ); } + +#[test] +fn fuzzed_unicode_slice() { + let d = "{eeuuu{b&{!!&{!!11{{ + 0!(!1q҄א!)!!!!!!n!"; + assert!(Ast::from_str(d, &Syntax::default()).is_err()); +}
Fuzzing askama_parser results in panic Hi, fuzzing `askama_parser` resulted in panic at following line. https://github.com/djc/askama/blob/43e92aa3b6b9cd967a70bd0fd54d1f087d6ed76b/askama_parser/src/expr.rs#L290 I suppose it happens because crash input contains Cyrillic letters which are multi-byte and we need exact byte indices to avoid such panic in `[..]` notation. ```rust #[test] fn testing() { let d = "{eeuuu{b&{!!&{!!11{{ 0!(!1q҄א!)!!!!!!n!"; if let Ok(_) = Ast::from_str(d, &Syntax::default()) {} } ``` ``` running 1 test thread 'tests::testing' panicked at 'byte index 6 is not a char boundary; it is inside 'א' (bytes 5..7) of `!1q҄א!)!!!!!!n!`', askama_parser/src/expr.rs:290:22 stack backtrace: ```
2023-09-11T09:42:00Z
0.12
2023-09-11T10:19:21Z
4dab5f91ba15e7c238ddf6223ec7b45eef32cab4
[ "tests::fuzzed_unicode_slice" ]
[ "tests::change_delimiters_parse_filter", "tests::test_missing_space_after_kw", "tests::test_invalid_block - should panic", "tests::test_parse_comments", "tests::test_associativity", "tests::test_parse_const", "tests::test_parse_numbers", "tests::test_odd_calls", "tests::test_parse_root_path", "tes...
[]
[]
auto_2025-06-03
rinja-rs/askama
837
rinja-rs__askama-837
[ "836" ]
9de9af4a006021a63f705e420be4cdef3eb6af82
diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -1373,7 +1373,7 @@ impl<'a> Generator<'a> { } Expr::Group(ref inner) => self.visit_group(buf, inner)?, Expr::Call(ref obj, ref args) => self.visit_call(buf, obj, args)?, - Expr::RustMacro(name, args) => self.visit_rust_macro(buf, name, args), + Expr::RustMacro(ref path, args) => self.visit_rust_macro(buf, path, args), Expr::Try(ref expr) => self.visit_try(buf, expr.as_ref())?, Expr::Tuple(ref exprs) => self.visit_tuple(buf, exprs)?, }) diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -1390,8 +1390,8 @@ impl<'a> Generator<'a> { Ok(DisplayWrap::Unwrapped) } - fn visit_rust_macro(&mut self, buf: &mut Buffer, name: &str, args: &str) -> DisplayWrap { - buf.write(name); + fn visit_rust_macro(&mut self, buf: &mut Buffer, path: &[&str], args: &str) -> DisplayWrap { + self.visit_path(buf, path); buf.write("!("); buf.write(args); buf.write(")"); diff --git a/askama_derive/src/parser/expr.rs b/askama_derive/src/parser/expr.rs --- a/askama_derive/src/parser/expr.rs +++ b/askama_derive/src/parser/expr.rs @@ -4,9 +4,10 @@ use nom::branch::alt; use nom::bytes::complete::{tag, take_till}; use nom::character::complete::char; use nom::combinator::{cut, map, not, opt, peek, recognize}; +use nom::error::ErrorKind; use nom::multi::{fold_many0, many0, separated_list0, separated_list1}; use nom::sequence::{delimited, pair, preceded, terminated, tuple}; -use nom::IResult; +use nom::{error_position, IResult}; use super::{ bool_lit, char_lit, identifier, nested_parenthesis, not_ws, num_lit, path, str_lit, ws, diff --git a/askama_derive/src/parser/expr.rs b/askama_derive/src/parser/expr.rs --- a/askama_derive/src/parser/expr.rs +++ b/askama_derive/src/parser/expr.rs @@ -30,7 +31,7 @@ pub(crate) enum Expr<'a> { Group(Box<Expr<'a>>), Tuple(Vec<Expr<'a>>), Call(Box<Expr<'a>>, Vec<Expr<'a>>), - RustMacro(&'a str, &'a str), + RustMacro(Vec<&'a str>, &'a str), Try(Box<Expr<'a>>), } diff --git a/askama_derive/src/parser/expr.rs b/askama_derive/src/parser/expr.rs --- a/askama_derive/src/parser/expr.rs +++ b/askama_derive/src/parser/expr.rs @@ -183,7 +184,6 @@ fn expr_single(i: &str) -> IResult<&str, Expr<'_>> { expr_str_lit, expr_char_lit, expr_path, - expr_rust_macro, expr_array_lit, expr_var, expr_group, diff --git a/askama_derive/src/parser/expr.rs b/askama_derive/src/parser/expr.rs --- a/askama_derive/src/parser/expr.rs +++ b/askama_derive/src/parser/expr.rs @@ -194,6 +194,8 @@ enum Suffix<'a> { Attr(&'a str), Index(Expr<'a>), Call(Vec<Expr<'a>>), + // The value is the arguments of the macro call. + MacroCall(&'a str), Try, } diff --git a/askama_derive/src/parser/expr.rs b/askama_derive/src/parser/expr.rs --- a/askama_derive/src/parser/expr.rs +++ b/askama_derive/src/parser/expr.rs @@ -218,6 +220,16 @@ fn expr_call(i: &str) -> IResult<&str, Suffix<'_>> { map(arguments, Suffix::Call)(i) } +fn expr_macro(i: &str) -> IResult<&str, Suffix<'_>> { + preceded( + pair(ws(char('!')), char('(')), + cut(terminated( + map(recognize(nested_parenthesis), Suffix::MacroCall), + char(')'), + )), + )(i) +} + fn expr_try(i: &str) -> IResult<&str, Suffix<'_>> { map(preceded(take_till(not_ws), char('?')), |_| Suffix::Try)(i) } diff --git a/askama_derive/src/parser/expr.rs b/askama_derive/src/parser/expr.rs --- a/askama_derive/src/parser/expr.rs +++ b/askama_derive/src/parser/expr.rs @@ -256,28 +268,26 @@ fn expr_prefix(i: &str) -> IResult<&str, Expr<'_>> { fn expr_suffix(i: &str) -> IResult<&str, Expr<'_>> { let (mut i, mut expr) = expr_single(i)?; loop { - let (j, suffix) = opt(alt((expr_attr, expr_index, expr_call, expr_try)))(i)?; - i = j; + let (j, suffix) = opt(alt(( + expr_attr, expr_index, expr_call, expr_try, expr_macro, + )))(i)?; match suffix { Some(Suffix::Attr(attr)) => expr = Expr::Attr(expr.into(), attr), Some(Suffix::Index(index)) => expr = Expr::Index(expr.into(), index.into()), Some(Suffix::Call(args)) => expr = Expr::Call(expr.into(), args), Some(Suffix::Try) => expr = Expr::Try(expr.into()), + Some(Suffix::MacroCall(args)) => match expr { + Expr::Path(path) => expr = Expr::RustMacro(path, args), + Expr::Var(name) => expr = Expr::RustMacro(vec![name], args), + _ => return Err(nom::Err::Failure(error_position!(i, ErrorKind::Tag))), + }, None => break, } + i = j; } Ok((i, expr)) } -fn macro_arguments(i: &str) -> IResult<&str, &str> { - delimited(char('('), recognize(nested_parenthesis), char(')'))(i) -} - -fn expr_rust_macro(i: &str) -> IResult<&str, Expr<'_>> { - let (i, (mname, _, args)) = tuple((identifier, char('!'), macro_arguments))(i)?; - Ok((i, Expr::RustMacro(mname, args))) -} - macro_rules! expr_prec_layer { ( $name:ident, $inner:ident, $op:expr ) => { fn $name(i: &str) -> IResult<&str, Expr<'_>> {
diff --git a/askama_derive/src/parser/tests.rs b/askama_derive/src/parser/tests.rs --- a/askama_derive/src/parser/tests.rs +++ b/askama_derive/src/parser/tests.rs @@ -221,6 +221,51 @@ fn test_parse_root_path() { ); } +#[test] +fn test_rust_macro() { + let syntax = Syntax::default(); + assert_eq!( + super::parse("{{ vec!(1, 2, 3) }}", &syntax).unwrap(), + vec![Node::Expr( + Ws(None, None), + Expr::RustMacro(vec!["vec"], "1, 2, 3",), + )], + ); + assert_eq!( + super::parse("{{ alloc::vec!(1, 2, 3) }}", &syntax).unwrap(), + vec![Node::Expr( + Ws(None, None), + Expr::RustMacro(vec!["alloc", "vec"], "1, 2, 3",), + )], + ); + assert_eq!( + super::parse("{{a!()}}", &syntax).unwrap(), + [Node::Expr(Ws(None, None), Expr::RustMacro(vec!["a"], ""))], + ); + assert_eq!( + super::parse("{{a !()}}", &syntax).unwrap(), + [Node::Expr(Ws(None, None), Expr::RustMacro(vec!["a"], ""))], + ); + assert_eq!( + super::parse("{{a! ()}}", &syntax).unwrap(), + [Node::Expr(Ws(None, None), Expr::RustMacro(vec!["a"], ""))], + ); + assert_eq!( + super::parse("{{a ! ()}}", &syntax).unwrap(), + [Node::Expr(Ws(None, None), Expr::RustMacro(vec!["a"], ""))], + ); + assert_eq!( + super::parse("{{A!()}}", &syntax).unwrap(), + [Node::Expr(Ws(None, None), Expr::RustMacro(vec!["A"], ""),)], + ); + assert_eq!( + &*super::parse("{{a.b.c!( hello )}}", &syntax) + .unwrap_err() + .msg, + "problems parsing template source at row 1, column 7 near:\n\"!( hello )}}\"", + ); +} + #[test] fn change_delimiters_parse_filter() { let syntax = Syntax { diff --git /dev/null b/testing/templates/rust-macros-full-path.html new file mode 100644 --- /dev/null +++ b/testing/templates/rust-macros-full-path.html @@ -0,0 +1,1 @@ +Hello, {{ foo::hello2!() }}! diff --git a/testing/tests/rust_macro.rs b/testing/tests/rust_macro.rs --- a/testing/tests/rust_macro.rs +++ b/testing/tests/rust_macro.rs @@ -11,11 +11,31 @@ macro_rules! hello { struct RustMacrosTemplate {} #[test] -fn main() { +fn macro_basic() { let template = RustMacrosTemplate {}; assert_eq!("Hello, world!", template.render().unwrap()); } +mod foo { + macro_rules! hello2 { + () => { + "world" + }; + } + + pub(crate) use hello2; +} + +#[derive(Template)] +#[template(path = "rust-macros-full-path.html")] +struct RustMacrosFullPathTemplate {} + +#[test] +fn macro_full_path() { + let template = RustMacrosFullPathTemplate {}; + assert_eq!("Hello, world!", template.render().unwrap()); +} + macro_rules! call_a_or_b_on_tail { ((a: $a:expr, b: $b:expr, c: $c:expr), call a: $($tail:expr),*) => { ($a)($($tail),*) diff --git a/testing/tests/rust_macro.rs b/testing/tests/rust_macro.rs --- a/testing/tests/rust_macro.rs +++ b/testing/tests/rust_macro.rs @@ -47,7 +67,7 @@ fn day(_: u16, _: &str, d: u8) -> u8 { struct RustMacrosArgTemplate {} #[test] -fn args() { +fn macro_with_args() { let template = RustMacrosArgTemplate {}; assert_eq!("2021\nJuly\n2", template.render().unwrap()); }
Parse error when using macro with expanded module path I am making a crate that allows people to embed icons from Iconify at compile time, but I ran into a little snag. Tried on main and 0.12. Only happens when using a macro, normal functions work fine. The intended usage is: ```jsx <body> <h1>Hello</h1> {{ iconify::svg!("mdi:home")|safe }} </body> ``` But it gives me a parse error: ``` error: problems parsing template source at row 5, column 19 near: "!(\"mdi:home\") }}\r\n</body>\r\n</html>\r" ``` I can work around it by importing the macro (below compiles fine), but I'd prefer being able to keep the module path so I don't need to. ```jsx {{ svg!("mdi:home")|safe }} ```
Huh, I guess there's some subtlety in the parser relating to the combination of a path, the macro call and the filter. Care to submit a PR? Sure, I'll take a jab at it. Macro invocations are parsed specially, but they should actually be simply suffix expressions, and be handled like normal function calls: https://github.com/djc/askama/blob/c9613ff6029ee58dc3f94c3dd955b905ed7fc9ef/askama_derive/src/parser/expr.rs#L256-L270
2023-07-05T21:49:42Z
0.12
2023-07-24T09:39:14Z
4dab5f91ba15e7c238ddf6223ec7b45eef32cab4
[ "config::tests::find_absolute", "config::tests::find_relative", "config::tests::add_syntax", "config::tests::escape_modes", "config::tests::add_syntax_two", "config::tests::find_relative_sub", "config::tests::get_source", "config::tests::find_relative_nonexistent - should panic", "config::tests::ill...
[]
[]
[]
auto_2025-06-03
rinja-rs/askama
965
rinja-rs__askama-965
[ "962", "961" ]
4dab5f91ba15e7c238ddf6223ec7b45eef32cab4
diff --git a/askama/Cargo.toml b/askama/Cargo.toml --- a/askama/Cargo.toml +++ b/askama/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "askama" -version = "0.12.1" +version = "0.13.0" description = "Type-safe, compiled Jinja-like templates for Rust" documentation = "https://docs.rs/askama" keywords = ["markup", "template", "jinja2", "html"] diff --git a/askama/Cargo.toml b/askama/Cargo.toml --- a/askama/Cargo.toml +++ b/askama/Cargo.toml @@ -39,7 +39,7 @@ mime = [] mime_guess = [] [dependencies] -askama_derive = { version = "0.12.0", path = "../askama_derive" } +askama_derive = { version = "0.13", path = "../askama_derive" } askama_escape = { version = "0.10.3", path = "../askama_escape" } comrak = { version = "0.21", optional = true, default-features = false } dep_humansize = { package = "humansize", version = "2", optional = true } diff --git a/askama_actix/Cargo.toml b/askama_actix/Cargo.toml --- a/askama_actix/Cargo.toml +++ b/askama_actix/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "askama_actix" -version = "0.14.0" +version = "0.15.0" description = "Actix-Web integration for Askama templates" documentation = "https://docs.rs/askama" keywords = ["markup", "template", "jinja2", "html"] diff --git a/askama_actix/Cargo.toml b/askama_actix/Cargo.toml --- a/askama_actix/Cargo.toml +++ b/askama_actix/Cargo.toml @@ -15,7 +15,7 @@ rust-version = "1.65" [dependencies] actix-web = { version = "4", default-features = false } -askama = { version = "0.12", path = "../askama", default-features = false, features = ["with-actix-web"] } +askama = { version = "0.13", path = "../askama", default-features = false, features = ["with-actix-web"] } [dev-dependencies] actix-rt = { version = "2", default-features = false } diff --git a/askama_axum/Cargo.toml b/askama_axum/Cargo.toml --- a/askama_axum/Cargo.toml +++ b/askama_axum/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "askama_axum" -version = "0.4.0" +version = "0.5.0" edition = "2021" rust-version = "1.65" description = "Axum integration for Askama templates" diff --git a/askama_axum/Cargo.toml b/askama_axum/Cargo.toml --- a/askama_axum/Cargo.toml +++ b/askama_axum/Cargo.toml @@ -14,7 +14,7 @@ workspace = ".." readme = "README.md" [dependencies] -askama = { version = "0.12", path = "../askama", default-features = false, features = ["with-axum", "mime", "mime_guess"] } +askama = { version = "0.13", path = "../askama", default-features = false, features = ["with-axum", "mime", "mime_guess"] } axum-core = "0.4" http = "1.0" diff --git a/askama_derive/Cargo.toml b/askama_derive/Cargo.toml --- a/askama_derive/Cargo.toml +++ b/askama_derive/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "askama_derive" -version = "0.12.5" +version = "0.13.0" description = "Procedural macro package for Askama" homepage = "https://github.com/djc/askama" repository = "https://github.com/djc/askama" diff --git a/askama_derive/src/config.rs b/askama_derive/src/config.rs --- a/askama_derive/src/config.rs +++ b/askama_derive/src/config.rs @@ -5,7 +5,7 @@ use std::{env, fs}; #[cfg(feature = "serde")] use serde::Deserialize; -use crate::CompileError; +use crate::{CompileError, CRATE}; use parser::node::Whitespace; use parser::Syntax; diff --git a/askama_derive/src/config.rs b/askama_derive/src/config.rs --- a/askama_derive/src/config.rs +++ b/askama_derive/src/config.rs @@ -93,7 +93,7 @@ impl<'a> Config<'a> { } } for (extensions, path) in DEFAULT_ESCAPERS { - escapers.push((str_set(extensions), (*path).to_string())); + escapers.push((str_set(extensions), format!("{CRATE}{path}"))); } Ok(Config { diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -5,7 +5,7 @@ use std::{cmp, hash, mem, str}; use crate::config::WhitespaceHandling; use crate::heritage::{Context, Heritage}; use crate::input::{Source, TemplateInput}; -use crate::CompileError; +use crate::{CompileError, CRATE}; use parser::node::{ Call, Comment, CondTest, If, Include, Let, Lit, Loop, Match, Target, Whitespace, Ws, diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -90,11 +90,10 @@ impl<'a> Generator<'a> { ctx: &'a Context<'_>, buf: &mut Buffer, ) -> Result<(), CompileError> { - self.write_header(buf, "::askama::Template", None)?; - buf.writeln( - "fn render_into(&self, writer: &mut (impl ::std::fmt::Write + ?Sized)) -> \ - ::askama::Result<()> {", - )?; + self.write_header(buf, &format!("{CRATE}::Template"), None)?; + buf.write("fn render_into(&self, writer: &mut (impl ::std::fmt::Write + ?Sized)) -> "); + buf.write(CRATE); + buf.writeln("::Result<()> {")?; // Make sure the compiler understands that the generated code depends on the template files. for path in self.contexts.keys() { diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -121,7 +120,8 @@ impl<'a> Generator<'a> { }?; self.flush_ws(Ws(None, None)); - buf.writeln("::askama::Result::Ok(())")?; + buf.write(CRATE); + buf.writeln("::Result::Ok(())")?; buf.writeln("}")?; buf.writeln("const EXTENSION: ::std::option::Option<&'static ::std::primitive::str> = ")?; diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -145,7 +145,8 @@ impl<'a> Generator<'a> { self.write_header(buf, "::std::fmt::Display", None)?; buf.writeln("#[inline]")?; buf.writeln("fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {")?; - buf.writeln("::askama::Template::render_into(self, f).map_err(|_| ::std::fmt::Error {})")?; + buf.write(CRATE); + buf.writeln("::Template::render_into(self, f).map_err(|_| ::std::fmt::Error {})")?; buf.writeln("}")?; buf.writeln("}") } diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -226,13 +227,13 @@ impl<'a> Generator<'a> { #where_clause ) ))?; - buf.writeln("type Error = ::askama::Error;")?; + buf.writeln("type Error = ::askama_hyper::Error;")?; buf.writeln("#[inline]")?; buf.writeln(&format!( "{} {{", quote!(fn try_from(value: &#ident #orig_ty_generics) -> Result<Self, Self::Error>) ))?; - buf.writeln("::askama::Template::render(value).map(Into::into)")?; + buf.writeln("::askama_hyper::Template::render(value).map(Into::into)")?; buf.writeln("}")?; buf.writeln("}") } diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -307,7 +308,7 @@ impl<'a> Generator<'a> { buf.writeln("#[inline]")?; buf.writeln( "fn respond_to(self, _: &'askama1 ::askama_rocket::Request) \ - -> ::askama_rocket::Result<'askama2> {", + -> ::askama_rocket::RocketResult<'askama2> {", )?; buf.writeln("::askama_rocket::respond(&self)")?; diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -324,9 +325,10 @@ impl<'a> Generator<'a> { None, )?; buf.writeln( - "type Error = ::askama_tide::askama::Error;\n\ + "type Error = ::askama_tide::Error;\n\ #[inline]\n\ - fn try_into(self) -> ::askama_tide::askama::Result<::askama_tide::tide::Body> {", + fn try_into(self) -> \ + ::askama_tide::Result<::askama_tide::tide::Body> {", )?; buf.writeln("::askama_tide::try_into_body(&self)")?; buf.writeln("}")?; diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -638,7 +640,9 @@ impl<'a> Generator<'a> { self.locals.push(); buf.write("for ("); self.visit_target(buf, true, true, &loop_block.var); - buf.writeln(", _loop_item) in ::askama::helpers::TemplateLoop::new(_iter) {")?; + buf.write(", _loop_item) in "); + buf.write(CRATE); + buf.writeln("::helpers::TemplateLoop::new(_iter) {")?; if has_else_nodes { buf.writeln("_did_loop = true;")?; diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -1046,7 +1050,7 @@ impl<'a> Generator<'a> { let expression = match wrapped { Wrapped => expr_buf.buf, Unwrapped => format!( - "::askama::MarkupDisplay::new_unsafe(&({}), {})", + "{CRATE}::MarkupDisplay::new_unsafe(&({}), {})", expr_buf.buf, self.input.escaper ), }; diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -1166,7 +1170,9 @@ impl<'a> Generator<'a> { ) -> Result<DisplayWrap, CompileError> { buf.write("::core::result::Result::map_err("); self.visit_expr(buf, expr)?; - buf.write(", |err| ::askama::shared::Error::Custom(::core::convert::Into::into(err)))?"); + buf.write(", |err| "); + buf.write(CRATE); + buf.write("::shared::Error::Custom(::core::convert::Into::into(err)))?"); Ok(DisplayWrap::Unwrapped) } diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -1201,7 +1207,7 @@ impl<'a> Generator<'a> { }; buf.write(&format!( - "::askama::filters::markdown({}, &", + "{CRATE}::filters::markdown({}, &", self.input.escaper )); self.visit_expr(buf, md)?; diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -1273,11 +1279,11 @@ impl<'a> Generator<'a> { const FILTERS: [&str; 2] = ["safe", "yaml"]; if FILTERS.contains(&name) { buf.write(&format!( - "::askama::filters::{}({}, ", + "{CRATE}::filters::{}({}, ", name, self.input.escaper )); } else if crate::BUILT_IN_FILTERS.contains(&name) { - buf.write(&format!("::askama::filters::{name}(")); + buf.write(&format!("{CRATE}::filters::{name}(")); } else { buf.write(&format!("filters::{name}(")); } diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -1313,7 +1319,8 @@ impl<'a> Generator<'a> { .ok_or_else(|| CompileError::from("invalid escaper for escape filter"))?, None => self.input.escaper, }; - buf.write("::askama::filters::escape("); + buf.write(CRATE); + buf.write("::filters::escape("); buf.write(escaper); buf.write(", "); self._visit_args(buf, &args[..1])?; diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -1366,7 +1373,8 @@ impl<'a> Generator<'a> { buf: &mut Buffer, args: &[Expr<'_>], ) -> Result<(), CompileError> { - buf.write("::askama::filters::join((&"); + buf.write(CRATE); + buf.write("::filters::join((&"); for (i, arg) in args.iter().enumerate() { if i > 0 { buf.write(", &"); diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -1476,7 +1484,9 @@ impl<'a> Generator<'a> { buf.writeln(");")?; buf.writeln("let _len = _cycle.len();")?; buf.writeln("if _len == 0 {")?; - buf.writeln("return ::core::result::Result::Err(::askama::Error::Fmt(::core::fmt::Error));")?; + buf.write("return ::core::result::Result::Err("); + buf.write(CRATE); + buf.writeln("::Error::Fmt(::core::fmt::Error));")?; buf.writeln("}")?; buf.writeln("_cycle[_loop_item.index % _len]")?; buf.writeln("})")?; diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -1815,6 +1825,7 @@ impl Buffer { } self.start = false; } + self.buf.push_str(s); } diff --git a/askama_derive/src/lib.rs b/askama_derive/src/lib.rs --- a/askama_derive/src/lib.rs +++ b/askama_derive/src/lib.rs @@ -156,3 +156,23 @@ const BUILT_IN_FILTERS: &[&str] = &[ "markdown", "yaml", ]; + +const CRATE: &str = if cfg!(feature = "with-actix-web") { + "::askama_actix" +} else if cfg!(feature = "with-axum") { + "::askama_axum" +} else if cfg!(feature = "with-gotham") { + "::askama_gotham" +} else if cfg!(feature = "with-hyper") { + "::askama_hyper" +} else if cfg!(feature = "with-mendes") { + "::askama_mendes" +} else if cfg!(feature = "with-rocket") { + "::askama_rocket" +} else if cfg!(feature = "with-tide") { + "::askama_tide" +} else if cfg!(feature = "with-warp") { + "::askama_warp" +} else { + "::askama" +}; diff --git a/askama_gotham/Cargo.toml b/askama_gotham/Cargo.toml --- a/askama_gotham/Cargo.toml +++ b/askama_gotham/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "askama_gotham" -version = "0.14.0" +version = "0.15.0" description = "Gotham integration for Askama templates" documentation = "https://docs.rs/askama" keywords = ["markup", "template", "jinja2", "html"] diff --git a/askama_gotham/Cargo.toml b/askama_gotham/Cargo.toml --- a/askama_gotham/Cargo.toml +++ b/askama_gotham/Cargo.toml @@ -14,7 +14,7 @@ edition = "2021" rust-version = "1.65" [dependencies] -askama = { version = "0.12", path = "../askama", default-features = false, features = ["with-gotham", "mime", "mime_guess"] } +askama = { version = "0.13", path = "../askama", default-features = false, features = ["with-gotham", "mime", "mime_guess"] } gotham = { version = "0.7", default-features = false } [dev-dependencies] diff --git a/askama_hyper/Cargo.toml b/askama_hyper/Cargo.toml --- a/askama_hyper/Cargo.toml +++ b/askama_hyper/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "askama_hyper" -version = "0.1.0" +version = "0.2.0" description = "Hyper integration for Askama templates" documentation = "https://docs.rs/askama" keywords = ["markup", "template", "jinja2", "html"] diff --git a/askama_hyper/Cargo.toml b/askama_hyper/Cargo.toml --- a/askama_hyper/Cargo.toml +++ b/askama_hyper/Cargo.toml @@ -14,7 +14,7 @@ edition = "2021" rust-version = "1.65" [dependencies] -askama = { version = "0.12", path = "../askama", default-features = false, features = ["with-hyper"] } +askama = { version = "0.13", path = "../askama", default-features = false, features = ["with-hyper"] } hyper = { version = "0.14", default-features = false } [dev-dependencies] diff --git a/askama_mendes/Cargo.toml b/askama_mendes/Cargo.toml --- a/askama_mendes/Cargo.toml +++ b/askama_mendes/Cargo.toml @@ -14,7 +14,7 @@ edition = "2021" rust-version = "1.65" [dependencies] -askama = { version = "0.12", path = "../askama", default-features = false, features = ["with-mendes", "mime", "mime_guess"] } +askama = { version = "0.13", path = "../askama", default-features = false, features = ["with-mendes", "mime", "mime_guess"] } mendes = "0.5.0" [dev-dependencies] diff --git a/askama_rocket/Cargo.toml b/askama_rocket/Cargo.toml --- a/askama_rocket/Cargo.toml +++ b/askama_rocket/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "askama_rocket" -version = "0.12.0" +version = "0.13.0" description = "Rocket integration for Askama templates" documentation = "https://docs.rs/askama" keywords = ["markup", "template", "jinja2", "html"] diff --git a/askama_rocket/Cargo.toml b/askama_rocket/Cargo.toml --- a/askama_rocket/Cargo.toml +++ b/askama_rocket/Cargo.toml @@ -14,8 +14,8 @@ edition = "2021" rust-version = "1.65" [dependencies] -askama = { version = "0.12", path = "../askama", default-features = false, features = ["with-rocket", "mime", "mime_guess"] } -rocket = { version = "0.5.0", default-features = false } +askama = { version = "0.13", path = "../askama", default-features = false, features = ["with-rocket", "mime", "mime_guess"] } +rocket = { version = "0.5", default-features = false } [dev-dependencies] futures-lite = "2.0.0" diff --git a/askama_rocket/src/lib.rs b/askama_rocket/src/lib.rs --- a/askama_rocket/src/lib.rs +++ b/askama_rocket/src/lib.rs @@ -8,9 +8,9 @@ pub use askama::*; use rocket::http::{Header, Status}; pub use rocket::request::Request; use rocket::response::Response; -pub use rocket::response::{Responder, Result}; +pub use rocket::response::{Responder, Result as RocketResult}; -pub fn respond<T: Template>(t: &T) -> Result<'static> { +pub fn respond<T: Template>(t: &T) -> RocketResult<'static> { let rsp = t.render().map_err(|_| Status::InternalServerError)?; Response::build() .header(Header::new("content-type", T::MIME_TYPE)) diff --git a/askama_tide/Cargo.toml b/askama_tide/Cargo.toml --- a/askama_tide/Cargo.toml +++ b/askama_tide/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "askama_tide" -version = "0.15.1" +version = "0.16.0" edition = "2021" rust-version = "1.65" description = "Tide integration for Askama templates" diff --git a/askama_tide/Cargo.toml b/askama_tide/Cargo.toml --- a/askama_tide/Cargo.toml +++ b/askama_tide/Cargo.toml @@ -13,7 +13,7 @@ workspace = ".." readme = "README.md" [dependencies] -askama = { version = "0.12", path = "../askama", default-features = false, features = ["with-tide"] } +askama = { version = "0.13", path = "../askama", default-features = false, features = ["with-tide"] } tide = { version = "0.16", default-features = false } [dev-dependencies] diff --git a/askama_tide/src/lib.rs b/askama_tide/src/lib.rs --- a/askama_tide/src/lib.rs +++ b/askama_tide/src/lib.rs @@ -2,7 +2,6 @@ #![deny(elided_lifetimes_in_paths)] #![deny(unreachable_pub)] -pub use askama; pub use tide; pub use askama::*; diff --git a/askama_warp/Cargo.toml b/askama_warp/Cargo.toml --- a/askama_warp/Cargo.toml +++ b/askama_warp/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "askama_warp" -version = "0.13.0" +version = "0.14.0" description = "Warp integration for Askama templates" documentation = "https://docs.rs/askama" keywords = ["markup", "template", "jinja2", "html"] diff --git a/askama_warp/Cargo.toml b/askama_warp/Cargo.toml --- a/askama_warp/Cargo.toml +++ b/askama_warp/Cargo.toml @@ -14,7 +14,7 @@ edition = "2021" rust-version = "1.65" [dependencies] -askama = { version = "0.12", path = "../askama", default-features = false, features = ["with-warp", "mime", "mime_guess"] } +askama = { version = "0.13", path = "../askama", default-features = false, features = ["with-warp", "mime", "mime_guess"] } warp = { version = "0.3", default-features = false } [dev-dependencies] diff --git a/book/src/getting_started.md b/book/src/getting_started.md --- a/book/src/getting_started.md +++ b/book/src/getting_started.md @@ -4,8 +4,7 @@ First, add the following to your crate's `Cargo.toml`: ```toml # in section [dependencies] -askama = "0.11.2" - +askama = "0.12.1" ``` Now create a directory called `templates` in your crate root. diff --git a/book/src/getting_started.md b/book/src/getting_started.md --- a/book/src/getting_started.md +++ b/book/src/getting_started.md @@ -35,3 +34,25 @@ fn main() { ``` You should now be able to compile and run this code. + +## Using integrations + +To use one of the [integrations](./integrations.md), with axum as an example: + +First, add this to your `Cargo.toml` instead: + +```toml +# in section [dependencies] +askama_axum = "0.4.0" +``` + +Then, import from askama_axum instead of askama: + +```rust +use askama_axum::Template; +``` + +This enables the implementation for axum's `IntoResponse` trait, +so an instance of the template can be returned as a response. + +For other integrations, import and use their crate accordingly. diff --git a/book/src/integrations.md b/book/src/integrations.md --- a/book/src/integrations.md +++ b/book/src/integrations.md @@ -2,6 +2,9 @@ ## Rocket integration +In your template definitions, replace `askama::Template` with +[`askama_rocket::Template`][askama_rocket]. + Enabling the `with-rocket` feature appends an implementation of Rocket's `Responder` trait for each template type. This makes it easy to trivially return a value of that type in a Rocket handler. See diff --git a/book/src/integrations.md b/book/src/integrations.md --- a/book/src/integrations.md +++ b/book/src/integrations.md @@ -14,6 +17,9 @@ handled by your error catcher. ## Actix-web integration +In your template definitions, replace `askama::Template` with +[`askama_actix::Template`][askama_actix]. + Enabling the `with-actix-web` feature appends an implementation of Actix-web's `Responder` trait for each template type. This makes it easy to trivially return a value of that type in an Actix-web handler. See diff --git a/book/src/integrations.md b/book/src/integrations.md --- a/book/src/integrations.md +++ b/book/src/integrations.md @@ -34,6 +43,9 @@ This preserves the response chain if any custom error handling needs to occur. ## Gotham integration +In your template definitions, replace `askama::Template` with +[`askama_gotham::Template`][askama_gotham]. + Enabling the `with-gotham` feature appends an implementation of Gotham's `IntoResponse` trait for each template type. This makes it easy to trivially return a value of that type in a Gotham handler. See
diff --git a/askama_derive/src/config.rs b/askama_derive/src/config.rs --- a/askama_derive/src/config.rs +++ b/askama_derive/src/config.rs @@ -299,9 +299,9 @@ pub(crate) fn get_template_source(tpl_path: &Path) -> std::result::Result<String static CONFIG_FILE_NAME: &str = "askama.toml"; static DEFAULT_SYNTAX_NAME: &str = "default"; static DEFAULT_ESCAPERS: &[(&[&str], &str)] = &[ - (&["html", "htm", "svg", "xml"], "::askama::Html"), - (&["md", "none", "txt", "yml", ""], "::askama::Text"), - (&["j2", "jinja", "jinja2"], "::askama::Html"), + (&["html", "htm", "svg", "xml"], "::Html"), + (&["md", "none", "txt", "yml", ""], "::Text"), + (&["j2", "jinja", "jinja2"], "::Html"), ]; #[cfg(test)] diff --git a/book/src/integrations.md b/book/src/integrations.md --- a/book/src/integrations.md +++ b/book/src/integrations.md @@ -22,6 +28,9 @@ from the Askama test suite for more on how to integrate. ## Axum integration +In your template definitions, replace `askama::Template` with +[`askama_axum::Template`][askama_axum]. + Enabling the `with-axum` feature appends an implementation of Axum's `IntoResponse` trait for each template type. This makes it easy to trivially return a value of that type in a Axum handler. See diff --git a/book/src/integrations.md b/book/src/integrations.md --- a/book/src/integrations.md +++ b/book/src/integrations.md @@ -46,6 +58,9 @@ This preserves the response chain if any custom error handling needs to occur. ## Warp integration +In your template definitions, replace `askama::Template` with +[`askama_warp::Template`][askama_warp]. + Enabling the `with-warp` feature appends an implementation of Warp's `Reply` trait for each template type. This makes it simple to return a template from a Warp filter. See [the example](https://github.com/djc/askama/blob/main/askama_warp/tests/warp.rs) diff --git a/book/src/integrations.md b/book/src/integrations.md --- a/book/src/integrations.md +++ b/book/src/integrations.md @@ -53,9 +68,19 @@ from the Askama test suite for more on how to integrate. ## Tide integration +In your template definitions, replace `askama::Template` with +[`askama_tide::Template`][askama_tide]. + Enabling the `with-tide` feature appends `Into<tide::Response>` and `TryInto<tide::Body>` implementations for each template type. This provides the ability for tide apps to build a response directly from a template, or to append a templated body to an existing `Response`. See [the example](https://github.com/djc/askama/blob/main/askama_tide/tests/tide.rs) from the Askama test suite for more on how to integrate. + +[askama_rocket]: https://docs.rs/askama_rocket +[askama_actix]: https://docs.rs/askama_actix +[askama_axum]: https://docs.rs/askama_axum +[askama_gotham]: https://docs.rs/askama_gotham +[askama_warp]: https://docs.rs/askama_warp +[askama_tide]: https://docs.rs/askama_tide diff --git a/testing/Cargo.toml b/testing/Cargo.toml --- a/testing/Cargo.toml +++ b/testing/Cargo.toml @@ -13,7 +13,7 @@ serde-json = ["serde_json", "askama/serde-json"] markdown = ["comrak", "askama/markdown"] [dependencies] -askama = { path = "../askama", version = "0.12" } +askama = { path = "../askama", version = "0.13" } comrak = { version = "0.21", default-features = false, optional = true } phf = { version = "0.11", features = ["macros" ]} serde_json = { version = "1.0", optional = true }
Remove the need to import askama itself when using integration crates While wording on https://github.com/djc/askama/issues/961, I wandered off to find the cause for the need as the title goes. A rough scan reveals that askama_derive generates some uses of `::askama::`, for example, this: https://github.com/djc/askama/blob/c2c9bd81708a0201aef49b83df89446e12a41817/askama_derive/src/generator.rs#L93-L96 … which leads to the need, as sub-dependencies can't be used directly. If they are removed, probably we can depend solely on integration crates? A possible way to do this might be something like ```rust #[inline] fn _askama(tail: &str) -> String { format!("::{}::askama{tail}", #[cfg(feature = "with-actix-web")] "askama_actix", #[cfg(feature = "with-axum")] "askama_axum", // ... ) } buf.write("fn render_into(&self, writer: &mut (impl ::std::fmt::Write + ?Sized)) -> ")?; buf.writeln(&_askama("::Result<()> {"))?; ``` … which isn't pretty, but works. Document how integration should be imported The integration section of the "book" looks like this: > ## {{TARGET}} integration > > Enabling the `with-{{target}}` feature appends an implementation of {{target}}'s {{corresponding_trait}} trait for each template type. This makes it easy to trivially return a value of that type in a {{target}} handler. (repeat for each target) However, a quick search shows that [you](https://github.com/djc/askama/issues/569#issuecomment-986238576) [need](https://github.com/djc/askama/issues/588#issuecomment-1002212182) [askama_{{target}}](https://github.com/djc/askama/issues/810#issuecomment-1497074654), not askama itself with `with-{{target}}` enabled (or [askama_{{target}} alone](https://github.com/djc/askama/issues/569#issuecomment-986553248)). On the other hand, the getting started section says nothing more than adding askama itself. If askama_{{target}} is the canonical way to use integration, maybe document that? I'm happy to PR with some advice on writing alignment.
Well, I wouldn't want to do this in a way that requires adding another intermediate allocation, but perhaps a newtype with a `Display` implementation could do the job. I'd be open to reviewing such a PR. How about checking for existence of `::askama::`, and if so, splitting the `&str` into head, prefix and tail, then 1) push head, 2) push `#[cfg]` activated prefix, 3) push tail? This would be a waste of branching in most cases, so probably a separate `fn writeln_askama` or something. Happy to review a PR that is mindful of the performance impact. Yeah, I guess we didn't update the documentation after the recommendation changes. The recommendation is indeed that you should import directly from askama_{{target}}, though you may also need to import from askama directly. Happy to review a PR along these lines!
2024-02-13T14:31:39Z
0.12
2024-03-05T10:34:46Z
4dab5f91ba15e7c238ddf6223ec7b45eef32cab4
[ "config::tests::find_absolute", "config::tests::find_relative", "config::tests::find_relative_sub", "config::tests::add_syntax", "config::tests::add_syntax_two", "config::tests::get_source", "config::tests::find_relative_nonexistent - should panic", "config::tests::test_config_whitespace_error", "co...
[]
[]
[]
auto_2025-06-03
rinja-rs/askama
951
rinja-rs__askama-951
[ "924" ]
29b25505b496510217a39606a5f72884867ef492
diff --git a/askama_parser/src/lib.rs b/askama_parser/src/lib.rs --- a/askama_parser/src/lib.rs +++ b/askama_parser/src/lib.rs @@ -349,9 +349,9 @@ fn path_or_identifier(i: &str) -> ParseResult<'_, PathOrIdentifier<'_>> { let rest = rest.as_deref().unwrap_or_default(); // The returned identifier can be assumed to be path if: - // - Contains both a lowercase and uppercase character, i.e. a type name like `None` - // - Doesn't contain any lowercase characters, i.e. it's a constant - // In short, if it contains any uppercase characters it's a path. + // - it is an absolute path (starts with `::`), or + // - it has multiple components (at least one `::`), or + // - the first letter is uppercase match (root, start, rest) { (Some(_), start, tail) => { let mut path = Vec::with_capacity(2 + tail.len()); diff --git a/askama_parser/src/lib.rs b/askama_parser/src/lib.rs --- a/askama_parser/src/lib.rs +++ b/askama_parser/src/lib.rs @@ -360,7 +360,7 @@ fn path_or_identifier(i: &str) -> ParseResult<'_, PathOrIdentifier<'_>> { path.extend(rest); Ok((i, PathOrIdentifier::Path(path))) } - (None, name, []) if !name.contains(char::is_uppercase) => { + (None, name, []) if name.chars().next().map_or(true, |c| c.is_lowercase()) => { Ok((i, PathOrIdentifier::Identifier(name))) } (None, start, tail) => {
diff --git a/testing/tests/simple.rs b/testing/tests/simple.rs --- a/testing/tests/simple.rs +++ b/testing/tests/simple.rs @@ -484,3 +484,23 @@ fn test_num_literals() { "[90, -90, 90, 2, 56, 240, 10.5, 10.5, 100000000000, 105000000000]", ); } + +#[allow(non_snake_case)] +#[derive(askama::Template)] +#[template(source = "{{ xY }}", ext = "txt")] +struct MixedCase { + xY: &'static str, +} + +/// Test that we can use mixed case in variable names +/// +/// We use some heuristics to distinguish paths (`std::str::String`) from +/// variable names (`foo`). Previously, this test would fail because any +/// name containing uppercase characters would be considered a path. +/// +/// https://github.com/djc/askama/issues/924 +#[test] +fn test_mixed_case() { + let template = MixedCase { xY: "foo" }; + assert_eq!(template.render().unwrap(), "foo"); +}
0.12.1 only allow lower-case variable name in template I don't know if I asked a stupid question, but I spend one day to find it ! my rust version is 1.74.0, I run it on my win11 and WSL ubuntu 22.04, see the same error below ```rust use askama::Template; #[derive(Template)] #[template(path = "hello.html")] struct HelloTemplate<'a> { nAme: &'a str, } fn main() { let hello = HelloTemplate { nAme: "world" }; println!("{}", hello.render().unwrap()); } ``` ```html Hello, {{ nAme }}! ``` ```toml [package] name = "hello" version = "0.1.0" edition = "2021" [dependencies] askama="0.12.1" ``` [xxx.DESKTOP-ABCDE12] ⮞ cargo run -p hello Compiling hello v0.1.0 (C:\xx\xx\xx\hello) error[E0425]: cannot find value `nAme` in this scope --> hello\src\main.rs:3:10 | 3 | #[derive(Template)] | ^^^^^^^^ | = note: this error originates in the derive macro `Template` (in Nightly builds, run with -Z macro-backtrace for more info) help: you might have meant to use the available field | 3 | #[derive(self.Template)] | +++++ For more information about this error, try `rustc --explain E0425`. error: could not compile `hello` (bin "hello") due to previous error
I'm new to axum, I have learn the docs https://djc.github.io/askama/askama.html, but it seems not have the request of lower case I suggest you get the macro expansion via Rust Analyzer or via the [debugging](https://djc.github.io/askama/debugging.html) features. I guess the code generator applies some heuristics that take variable name casing into account in a way that might be surprising. I just find that, the var name with upper case => Path(["nAme"]), the var name with lower case => Var("na")) Var("me")), but I don't know it is the purpose of Askama or not ? I don't find the code which product this difference either. ```html <h1>Hello, {{ na }} {{ nAme }} {{ me }} !</h1> ``` ```rust use askama::Template; #[derive(Template)] #[template(path = "hello.html", print = "all")] struct HelloTemplate<'a> { na: &'a str, nAme: &'a str, me: &'a str, } fn main() { println!("hello world"); } ``` ```shell [aaaa.DESKTOP-ABCDE] ⮞ cargo run -p hello Compiling hello v0.1.0 (C:\aaa\aaa\aaa\hello) [Lit(Lit { lws: "", val: "<h1>Hello,", rws: " " }), Expr(Ws(None, None), Var("na")), Lit(Lit { lws: " ", val: "", rws: "" }), Expr(Ws(None, None), Path(["nAme"])), Lit(Lit { lws: " ", val: "", rws: "" }), Expr(Ws(None, None), Var("me")), Lit(Lit { lws: " ", val: "!</h1>", rws: "" })] ...... error[E0425]: cannot find value `nAme` in this scope --> hello\src\main.rs:3:10 | 3 | #[derive(Template)] | ^^^^^^^^ | = note: this error originates in the derive macro `Template` (in Nightly builds, run with -Z macro-backtrace for more info) help: you might have meant to use the available field | 3 | #[derive(self.Template)] | +++++ For more information about this error, try `rustc --explain E0425`. error: could not compile `hello` (bin "hello") due to previous error ``` I ran in to the same issue. For some reason if you have uppercase, the code it generates fails. See this example ``` expr0 = &::askama::MarkupDisplay::new_unsafe(&(self.title), ::askama::Html), expr1 = &::askama::MarkupDisplay::new_unsafe(&(xxxYYY), ::askama::Html), ``` with uppercase, it doesnt add self. in front of the variable name. I couldn't not find any mention in the documentation for this. It's kind of an annoying limitation if intended. if I make YYY to lower case, it generates the following ``` expr0 = &::askama::MarkupDisplay::new_unsafe(&(self.title), ::askama::Html), expr1 = &::askama::MarkupDisplay::new_unsafe(&(self.xxxyyy), ::askama::Html), ``` You can get around it by just doing this in the html template `<h1>{{ self.xxxYYY }}</h1>` any reason for this behavior?
2024-01-18T09:50:05Z
0.12
2024-01-18T10:23:22Z
4dab5f91ba15e7c238ddf6223ec7b45eef32cab4
[ "test_attr", "test_comment", "test_composition", "test_constants", "test_define_string_var", "test_else", "test_else_if", "test_empty", "test_escape", "test_func_ref_call", "test_generics", "test_if", "test_literals", "test_index", "test_literals_escape", "test_minus", "test_negation...
[]
[]
[]
auto_2025-06-03
rinja-rs/askama
943
rinja-rs__askama-943
[ "330" ]
84c2094e871b7ef16ab51c77b4a3568794c75638
diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -1210,6 +1210,20 @@ impl<'a> Generator<'a> { Ok(DisplayWrap::Wrapped) } + fn _visit_as_ref_filter( + &mut self, + buf: &mut Buffer, + args: &[Expr<'_>], + ) -> Result<(), CompileError> { + let arg = match args { + [arg] => arg, + _ => return Err("unexpected argument(s) in `as_ref` filter".into()), + }; + buf.write("&"); + self.visit_expr(buf, arg)?; + Ok(()) + } + fn visit_filter( &mut self, buf: &mut Buffer, diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -1230,6 +1244,9 @@ impl<'a> Generator<'a> { return Ok(DisplayWrap::Unwrapped); } else if name == "markdown" { return self._visit_markdown_filter(buf, args); + } else if name == "as_ref" { + self._visit_as_ref_filter(buf, args)?; + return Ok(DisplayWrap::Wrapped); } if name == "tojson" { diff --git a/book/src/filters.md b/book/src/filters.md --- a/book/src/filters.md +++ b/book/src/filters.md @@ -21,6 +21,7 @@ but are disabled by default. Enable them with Cargo features (see below for more * **[Built-in filters][#built-in-filters]:** [`abs`][#abs], + [`as_ref`][#as_ref], [`capitalize`][#capitalize], [`center`][#center], [`escape|e`][#escape], diff --git a/book/src/filters.md b/book/src/filters.md --- a/book/src/filters.md +++ b/book/src/filters.md @@ -62,6 +63,23 @@ Output: 2 ``` +### as_ref +[#as_ref]: #as_ref + +Creates a reference to the given argument. + +``` +{{ "a"|as_ref }} +{{ self.x|as_ref }} +``` + +will become: + +``` +&a +&self.x +``` + ### capitalize [#capitalize]: #capitalize
diff --git a/testing/tests/filters.rs b/testing/tests/filters.rs --- a/testing/tests/filters.rs +++ b/testing/tests/filters.rs @@ -309,3 +309,17 @@ fn test_json_script() { r#"<script>var user = "\u003c/script\u003e\u003cbutton\u003eHacked!\u003c/button\u003e"</script>"# ); } + +#[derive(askama::Template)] +#[template(source = "{% let word = s|as_ref %}{{ word }}", ext = "html")] +struct LetBorrow { + s: String, +} + +#[test] +fn test_let_borrow() { + let template = LetBorrow { + s: "hello".to_owned(), + }; + assert_eq!(template.render().unwrap(), "hello") +}
Add support for reference operator (i.e. `{% let x = &y %}`) Sometimes while working with deeply nested structures, it would be useful to create an alias to a field, like say `{% let h = &parent.child.hash %}` At the moment the `&` unary operator is not supported.
Not supporting this has been a design goal from the start. If I remember correctly, your example should already work without `&`. > If I remember correctly, your example should already work without `&`. Unfortunately it doesn't (`hash` here is an owned `HashMap`, and all other structures are owned by `self`): ~~~~ error[E0507]: cannot move out of `self.nested_1.nested_2.hash` which is behind a shared reference --> /home/build/sources/testing/tests/simple.rs:406:10 | 406 | #[derive(askama::Template, Default)] | ^^^^^^^^^^^^^^^^ | | | move occurs because `self.nested_1.nested_2.hash` has type `std::collections::HashMap<&str, &str>`, which does not implement t he `Copy` trait | help: consider borrowing here: `&askama::Template` | = note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to previous error ~~~~ Hmm, okay. Perhaps we should eagerly take a reference in variable declarations (and then not do so when referencing variables later). I don't know this issue is still being tracked, by I solved by using a filter. ``` pub fn asref<'a, T>(s: &'a T) -> askama::Result<&'a T> { Ok(s) } ``` And on the template: ``` {% let doc = invoice.0|asref %} ``` It is also possible to use https://doc.rust-lang.org/std/borrow/trait.Borrow.html At least for my usecase where I needed to compare dates: ```html {% if (Utc::now() + Duration::days(1)).borrow() > delete_at %} {{ delete_at.format("%H:%M:%S") }} {% else %} {{ delete_at }} {% endif %} ```
2024-01-10T14:11:35Z
0.12
2024-01-12T10:10:23Z
4dab5f91ba15e7c238ddf6223ec7b45eef32cab4
[ "filter_escape", "filter_format", "filter_fmt", "filter_opt_escaper_html", "filter_opt_escaper_none", "into_numbers_fmt", "test_filter_let_filter", "test_filter_truncate", "test_join", "test_json", "test_json_attribute", "test_json_attribute2", "test_json_script", "test_my_filter", "test...
[]
[]
[]
auto_2025-06-03
rinja-rs/askama
911
rinja-rs__askama-911
[ "904" ]
6cbfde04514a90d4e24350c21ef490c40666d820
diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -1575,6 +1575,16 @@ impl<'a> Generator<'a> { } buf.write(name); } + Target::OrChain(targets) => match targets.first() { + None => buf.write("_"), + Some(first_target) => { + self.visit_target(buf, initialized, first_level, first_target); + for target in &targets[1..] { + buf.write(" | "); + self.visit_target(buf, initialized, first_level, target); + } + } + }, Target::Tuple(path, targets) => { buf.write(&path.join("::")); buf.write("("); diff --git a/askama_parser/src/node.rs b/askama_parser/src/node.rs --- a/askama_parser/src/node.rs +++ b/askama_parser/src/node.rs @@ -128,10 +128,23 @@ pub enum Target<'a> { CharLit(&'a str), BoolLit(&'a str), Path(Vec<&'a str>), + OrChain(Vec<Target<'a>>), } impl<'a> Target<'a> { + /// Parses multiple targets with `or` separating them pub(super) fn parse(i: &'a str) -> ParseResult<'a, Self> { + map( + separated_list1(ws(tag("or")), Self::parse_one), + |mut opts| match opts.len() { + 1 => opts.pop().unwrap(), + _ => Self::OrChain(opts), + }, + )(i) + } + + /// Parses a single target without an `or`, unless it is wrapped in parentheses. + fn parse_one(i: &'a str) -> ParseResult<'a, Self> { let mut opt_opening_paren = map(opt(ws(char('('))), |o| o.is_some()); let mut opt_closing_paren = map(opt(ws(char(')'))), |o| o.is_some()); let mut opt_opening_brace = map(opt(ws(char('{'))), |o| o.is_some());
diff --git /dev/null b/testing/templates/match-enum-or.html new file mode 100644 --- /dev/null +++ b/testing/templates/match-enum-or.html @@ -0,0 +1,8 @@ +The card is +{%- match suit %} + {%- when Suit::Clubs or Suit::Spades -%} + {{ " black" }} + {%- when Suit::Diamonds or Suit::Hearts -%} + {{ " red" }} +{%- endmatch %} + diff --git a/testing/tests/matches.rs b/testing/tests/matches.rs --- a/testing/tests/matches.rs +++ b/testing/tests/matches.rs @@ -195,3 +195,32 @@ fn test_match_with_comment() { let s = MatchWithComment { good: false }; assert_eq!(s.render().unwrap(), "bad"); } + +enum Suit { + Clubs, + Diamonds, + Hearts, + Spades, +} + +#[derive(Template)] +#[template(path = "match-enum-or.html")] +struct MatchEnumOrTemplate { + suit: Suit, +} + +#[test] +fn test_match_enum_or() { + let template = MatchEnumOrTemplate { suit: Suit::Clubs }; + assert_eq!(template.render().unwrap(), "The card is black\n"); + let template = MatchEnumOrTemplate { suit: Suit::Spades }; + assert_eq!(template.render().unwrap(), "The card is black\n"); + + let template = MatchEnumOrTemplate { suit: Suit::Hearts }; + assert_eq!(template.render().unwrap(), "The card is red\n"); + + let template = MatchEnumOrTemplate { + suit: Suit::Diamonds, + }; + assert_eq!(template.render().unwrap(), "The card is red\n"); +}
Feature request: enhance match to include multiple targets This has previously been discussed at https://github.com/djc/askama/issues/711#issuecomment-1794340598 but I would like to move it to its own issue as it can be implemented separately. The request is to enhance Askana's syntax for the `match` block (see https://djc.github.io/askama/template_syntax.html#match) to handle multiple targets in the same 'arm'. See https://doc.rust-lang.org/reference/expressions/match-expr.html for the Rust syntax in the Reference Manual. Note that a match arm can have multiple targets; the object of this feature request is to replicate this in Askama. (I am not requesting 'match arm guards' (`if` clauses)). So given code like ``` enum Suit {Clubs, Diamonds, Hearts, Spades} ``` one could write a template like ``` The card is {% match suit %} {% when Suit::Clubs or Suit::Spades %} black {% when Suit::Diamonds or Suit::Hearts %} red {% endmatch %} ``` Alternatively, `or` could be replaced by `|` in the proposed design, but I think Askama prefers keywords to symbols. Looking at the code, `combinator/mod.rs(587)`*ff* defines how match statements are stored in the parse structure and how the code is parsed into this structure, and line 232*ff* covers `when` arms. So the `target` field would need to be a vector of `Targets`, and the `when()` function would need to be able to parse the modified `when` syntax., and the `parse()` function for `Match` around 595 also would need changing. The `Match` structure is used in `generator.rs` around 544*ff* to generate the Rust code. This currently calls `visit_target` at 1559*ff* to generate the actual target; this would need to be changed around 576 to a call for each target and to output intervening `|` tokens. There is some code around `heritage.rs(93)`. I'm not sure what it does, but it looks like it moves the match arms without change, so maybe it does not require any change. Also, the documentation will need changing, of course. near `template_syntax.md(417)`*ff*. The test could look something like the following (in `testing/tests/matches.rs)`, with the template above in `testing/templates/match-enum.html`). ``` enum Suit {Clubs, Diamonds, Hearts, Spades} #[derive(Template)] #[template(path = "match-enum.html")] struct MatchEnumTemplate { item: Suit, } #[test] fn test_match_enum() { let s = MatchEnumTemplate { item: Suit::Clubs}; assert_eq!(s.render().unwrap(), "\nThe card is black\n"); let s = MatchEnumTemplate { item: Suit::Hearts}; assert_eq!(s.render().unwrap(), "\nThe card is red\n"); } ```
I'm happy to review a PR for this as proposed.
2023-11-19T18:50:18Z
0.12
2023-11-22T13:56:14Z
4dab5f91ba15e7c238ddf6223ec7b45eef32cab4
[ "test_match_custom_enum", "test_match_literal_char", "test_match_literal", "test_match_literal_num", "test_match_no_whitespace", "test_match_option", "test_match_option_bool", "test_match_option_result_option", "test_match_ref_deref", "test_match_without_with_keyword", "test_match_with_comment" ...
[]
[]
[]
auto_2025-06-03
rinja-rs/askama
910
rinja-rs__askama-910
[ "885" ]
80238d7f48fd86ef939e74df9fdc9678ee78a208
diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -727,7 +727,50 @@ impl<'a> Generator<'a> { args.len() ))); } - for (expr, arg) in std::iter::zip(args, &def.args) { + let mut named_arguments = HashMap::new(); + // Since named arguments can only be passed last, we only need to check if the last argument + // is a named one. + if let Some(Expr::NamedArgument(_, _)) = args.last() { + // First we check that all named arguments actually exist in the called item. + for arg in args.iter().rev() { + let Expr::NamedArgument(arg_name, _) = arg else { + break; + }; + if !def.args.iter().any(|arg| arg == arg_name) { + return Err(CompileError::from(format!( + "no argument named `{arg_name}` in macro {name:?}" + ))); + } + named_arguments.insert(arg_name, arg); + } + } + + // Handling both named and unnamed arguments requires to be careful of the named arguments + // order. To do so, we iterate through the macro defined arguments and then check if we have + // a named argument with this name: + // + // * If there is one, we add it and move to the next argument. + // * If there isn't one, then we pick the next argument (we can do it without checking + // anything since named arguments are always last). + let mut allow_positional = true; + for (index, arg) in def.args.iter().enumerate() { + let expr = match named_arguments.get(&arg) { + Some(expr) => { + allow_positional = false; + expr + } + None => { + if !allow_positional { + // If there is already at least one named argument, then it's not allowed + // to use unnamed ones at this point anymore. + return Err(CompileError::from(format!( + "cannot have unnamed argument (`{arg}`) after named argument in macro \ + {name:?}" + ))); + } + &args[index] + } + }; match expr { // If `expr` is already a form of variable then // don't reintroduce a new variable. This is diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -1104,6 +1147,7 @@ impl<'a> Generator<'a> { Expr::RustMacro(ref path, args) => self.visit_rust_macro(buf, path, args), Expr::Try(ref expr) => self.visit_try(buf, expr.as_ref())?, Expr::Tuple(ref exprs) => self.visit_tuple(buf, exprs)?, + Expr::NamedArgument(_, ref expr) => self.visit_named_argument(buf, expr)?, }) } diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -1504,6 +1548,15 @@ impl<'a> Generator<'a> { Ok(DisplayWrap::Unwrapped) } + fn visit_named_argument( + &mut self, + buf: &mut Buffer, + expr: &Expr<'_>, + ) -> Result<DisplayWrap, CompileError> { + self.visit_expr(buf, expr)?; + Ok(DisplayWrap::Unwrapped) + } + fn visit_array( &mut self, buf: &mut Buffer, diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -1913,6 +1966,7 @@ pub(crate) fn is_cacheable(expr: &Expr<'_>) -> bool { } Expr::Group(arg) => is_cacheable(arg), Expr::Tuple(args) => args.iter().all(is_cacheable), + Expr::NamedArgument(_, expr) => is_cacheable(expr), // We have too little information to tell if the expression is pure: Expr::Call(_, _) => false, Expr::RustMacro(_, _) => false, diff --git a/askama_parser/src/expr.rs b/askama_parser/src/expr.rs --- a/askama_parser/src/expr.rs +++ b/askama_parser/src/expr.rs @@ -1,3 +1,5 @@ +use std::borrow::Cow; +use std::collections::HashSet; use std::str; use nom::branch::alt; diff --git a/askama_parser/src/expr.rs b/askama_parser/src/expr.rs --- a/askama_parser/src/expr.rs +++ b/askama_parser/src/expr.rs @@ -12,7 +14,7 @@ use nom::sequence::{pair, preceded, terminated, tuple}; use super::{ char_lit, identifier, not_ws, num_lit, path_or_identifier, str_lit, ws, Level, PathOrIdentifier, }; -use crate::ParseResult; +use crate::{ErrorContext, ParseResult}; macro_rules! expr_prec_layer { ( $name:ident, $inner:ident, $op:expr ) => { diff --git a/askama_parser/src/expr.rs b/askama_parser/src/expr.rs --- a/askama_parser/src/expr.rs +++ b/askama_parser/src/expr.rs @@ -61,6 +63,7 @@ pub enum Expr<'a> { Attr(Box<Expr<'a>>, &'a str), Index(Box<Expr<'a>>, Box<Expr<'a>>), Filter(&'a str, Vec<Expr<'a>>), + NamedArgument(&'a str, Box<Expr<'a>>), Unary(&'a str, Box<Expr<'a>>), BinOp(&'a str, Box<Expr<'a>>, Box<Expr<'a>>), Range(&'a str, Option<Box<Expr<'a>>>, Option<Box<Expr<'a>>>), diff --git a/askama_parser/src/expr.rs b/askama_parser/src/expr.rs --- a/askama_parser/src/expr.rs +++ b/askama_parser/src/expr.rs @@ -72,17 +75,83 @@ pub enum Expr<'a> { } impl<'a> Expr<'a> { - pub(super) fn arguments(i: &'a str, level: Level) -> ParseResult<'a, Vec<Self>> { + pub(super) fn arguments( + i: &'a str, + level: Level, + is_template_macro: bool, + ) -> ParseResult<'a, Vec<Self>> { let (_, level) = level.nest(i)?; + let mut named_arguments = HashSet::new(); + let start = i; + preceded( ws(char('(')), cut(terminated( - separated_list0(char(','), ws(move |i| Self::parse(i, level))), + separated_list0( + char(','), + ws(move |i| { + // Needed to prevent borrowing it twice between this closure and the one + // calling `Self::named_arguments`. + let named_arguments = &mut named_arguments; + let has_named_arguments = !named_arguments.is_empty(); + + let (i, expr) = alt(( + move |i| { + Self::named_argument( + i, + level, + named_arguments, + start, + is_template_macro, + ) + }, + move |i| Self::parse(i, level), + ))(i)?; + if has_named_arguments && !matches!(expr, Self::NamedArgument(_, _)) { + Err(nom::Err::Failure(ErrorContext { + input: start, + message: Some(Cow::Borrowed( + "named arguments must always be passed last", + )), + })) + } else { + Ok((i, expr)) + } + }), + ), char(')'), )), )(i) } + fn named_argument( + i: &'a str, + level: Level, + named_arguments: &mut HashSet<&'a str>, + start: &'a str, + is_template_macro: bool, + ) -> ParseResult<'a, Self> { + if !is_template_macro { + // If this is not a template macro, we don't want to parse named arguments so + // we instead return an error which will allow to continue the parsing. + return Err(nom::Err::Error(error_position!(i, ErrorKind::Alt))); + } + + let (_, level) = level.nest(i)?; + let (i, (argument, _, value)) = + tuple((identifier, ws(char('=')), move |i| Self::parse(i, level)))(i)?; + if named_arguments.insert(argument) { + Ok((i, Self::NamedArgument(argument, Box::new(value)))) + } else { + Err(nom::Err::Failure(ErrorContext { + input: start, + message: Some(Cow::Owned(format!( + "named argument `{argument}` was passed more than once" + ))), + })) + } + } + pub(super) fn parse(i: &'a str, level: Level) -> ParseResult<'a, Self> { let (_, level) = level.nest(i)?; let range_right = move |i| { diff --git a/askama_parser/src/expr.rs b/askama_parser/src/expr.rs --- a/askama_parser/src/expr.rs +++ b/askama_parser/src/expr.rs @@ -122,7 +191,7 @@ impl<'a> Expr<'a> { let (i, (_, fname, args)) = tuple(( char('|'), ws(identifier), - opt(|i| Expr::arguments(i, level)), + opt(|i| Expr::arguments(i, level, false)), ))(i)?; Ok((i, (fname, args))) } diff --git a/askama_parser/src/expr.rs b/askama_parser/src/expr.rs --- a/askama_parser/src/expr.rs +++ b/askama_parser/src/expr.rs @@ -354,7 +423,7 @@ impl<'a> Suffix<'a> { fn call(i: &'a str, level: Level) -> ParseResult<'a, Self> { let (_, level) = level.nest(i)?; - map(move |i| Expr::arguments(i, level), Self::Call)(i) + map(move |i| Expr::arguments(i, level, false), Self::Call)(i) } fn r#try(i: &'a str) -> ParseResult<'a, Self> { diff --git a/askama_parser/src/node.rs b/askama_parser/src/node.rs --- a/askama_parser/src/node.rs +++ b/askama_parser/src/node.rs @@ -564,7 +564,7 @@ impl<'a> Call<'a> { cut(tuple(( opt(tuple((ws(identifier), ws(tag("::"))))), ws(identifier), - opt(ws(|nested| Expr::arguments(nested, s.level.get()))), + opt(ws(|nested| Expr::arguments(nested, s.level.get(), true))), opt(Whitespace::parse), ))), )); diff --git a/book/src/template_syntax.md b/book/src/template_syntax.md --- a/book/src/template_syntax.md +++ b/book/src/template_syntax.md @@ -564,7 +564,7 @@ You can define macros within your template by using `{% macro name(args) %}`, en You can then call it with `{% call name(args) %}`: -``` +```jinja {% macro heading(arg) %} <h1>{{arg}}</h1> diff --git a/book/src/template_syntax.md b/book/src/template_syntax.md --- a/book/src/template_syntax.md +++ b/book/src/template_syntax.md @@ -576,7 +576,7 @@ You can then call it with `{% call name(args) %}`: You can place macros in a separate file and use them in your templates by using `{% import %}`: -``` +```jinja {%- import "macro.html" as scope -%} {% call scope::heading(s) %} diff --git a/book/src/template_syntax.md b/book/src/template_syntax.md --- a/book/src/template_syntax.md +++ b/book/src/template_syntax.md @@ -584,6 +584,51 @@ You can place macros in a separate file and use them in your templates by using You can optionally specify the name of the macro in `endmacro`: -```html +```jinja {% macro heading(arg) %}<p>{{arg}}</p>{% endmacro heading %} ``` + +You can also specify arguments by their name (as defined in the macro): + +```jinja +{% macro heading(arg, bold) %} + +<h1>{{arg}} <b>{{bold}}</b></h1> + +{% endmacro %} + +{% call heading(bold="something", arg="title") %} +``` + +You can use whitespace characters around `=`: + +```jinja +{% call heading(bold = "something", arg = "title") %} +``` + +You can mix named and non-named arguments when calling a macro: + +``` +{% call heading("title", bold="something") %} +``` + +However please note than named arguments must always come **last**. + +Another thing to note, if a named argument is referring to an argument that would +be used for a non-named argument, it will error: + +```jinja +{% macro heading(arg1, arg2, arg3, arg4) %} +{% endmacro %} + +{% call heading("something", "b", arg4="ah", arg2="title") %} +``` + +In here it's invalid because `arg2` is the second argument and would be used by +`"b"`. So either you replace `"b"` with `arg3="b"` or you pass `"title"` before: + +```jinja +{% call heading("something", arg3="b", arg4="ah", arg2="title") %} +{# Equivalent of: #} +{% call heading("something", "title", "b", arg4="ah") %} +```
diff --git a/testing/tests/macro.rs b/testing/tests/macro.rs --- a/testing/tests/macro.rs +++ b/testing/tests/macro.rs @@ -95,3 +95,31 @@ fn test_macro_self_arg() { let t = MacroSelfArgTemplate { s: "foo" }; assert_eq!(t.render().unwrap(), "foo"); } + +#[derive(Template)] +#[template( + source = "{%- macro thrice(param1, param2) -%} +{{ param1 }} {{ param2 }} +{% endmacro -%} + +{%- call thrice(param1=2, param2=3) -%} +{%- call thrice(param2=3, param1=2) -%} +{%- call thrice(3, param2=2) -%} +", + ext = "html" +)] +struct MacroNamedArg; + +#[test] +// We check that it's always the correct values passed to the +// expected argument. +fn test_named_argument() { + assert_eq!( + MacroNamedArg.render().unwrap(), + "\ +2 3 +2 3 +3 2 +" + ); +} diff --git /dev/null b/testing/tests/ui/macro_named_argument.rs new file mode 100644 --- /dev/null +++ b/testing/tests/ui/macro_named_argument.rs @@ -0,0 +1,45 @@ +use askama::Template; + +#[derive(Template)] +#[template(source = "{%- macro thrice(param1, param2) -%} +{{ param1 }} {{ param2 }} +{%- endmacro -%} + +{%- call thrice(param1=2, param3=3) -%}", ext = "html")] +struct InvalidNamedArg; + +#[derive(Template)] +#[template(source = "{%- macro thrice(param1, param2) -%} +{{ param1 }} {{ param2 }} +{%- endmacro -%} + +{%- call thrice(param1=2, param1=3) -%}", ext = "html")] +struct InvalidNamedArg2; + +// Ensures that filters can't have named arguments. +#[derive(Template)] +#[template(source = "{%- macro thrice(param1, param2) -%} +{{ param1 }} {{ param2 }} +{%- endmacro -%} + +{%- call thrice(3, param1=2) | filter(param1=12) -%}", ext = "html")] +struct InvalidNamedArg3; + +// Ensures that named arguments can only be passed last. +#[derive(Template)] +#[template(source = "{%- macro thrice(param1, param2) -%} +{{ param1 }} {{ param2 }} +{%- endmacro -%} +{%- call thrice(param1=2, 3) -%}", ext = "html")] +struct InvalidNamedArg4; + +// Ensures that named arguments can't be used for arguments before them. +#[derive(Template)] +#[template(source = "{%- macro thrice(param1, param2) -%} +{{ param1 }} {{ param2 }} +{%- endmacro -%} +{%- call thrice(3, param1=2) -%}", ext = "html")] +struct InvalidNamedArg5; + +fn main() { +} diff --git /dev/null b/testing/tests/ui/macro_named_argument.stderr new file mode 100644 --- /dev/null +++ b/testing/tests/ui/macro_named_argument.stderr @@ -0,0 +1,44 @@ +error: no argument named `param3` in macro "thrice" + --> tests/ui/macro_named_argument.rs:3:10 + | +3 | #[derive(Template)] + | ^^^^^^^^ + | + = note: this error originates in the derive macro `Template` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: named argument `param1` was passed more than once + problems parsing template source at row 5, column 15 near: + "(param1=2, param1=3) -%}" + --> tests/ui/macro_named_argument.rs:11:10 + | +11 | #[derive(Template)] + | ^^^^^^^^ + | + = note: this error originates in the derive macro `Template` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: problems parsing template source at row 5, column 29 near: + "| filter(param1=12) -%}" + --> tests/ui/macro_named_argument.rs:20:10 + | +20 | #[derive(Template)] + | ^^^^^^^^ + | + = note: this error originates in the derive macro `Template` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: named arguments must always be passed last + problems parsing template source at row 4, column 15 near: + "(param1=2, 3) -%}" + --> tests/ui/macro_named_argument.rs:29:10 + | +29 | #[derive(Template)] + | ^^^^^^^^ + | + = note: this error originates in the derive macro `Template` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: cannot have unnamed argument (`param2`) after named argument in macro "thrice" + --> tests/ui/macro_named_argument.rs:37:10 + | +37 | #[derive(Template)] + | ^^^^^^^^ + | + = note: this error originates in the derive macro `Template` (in Nightly builds, run with -Z macro-backtrace for more info)
Allow to have named arguments in macro It'd pretty nice to be able to have named arguments. For example: ``` {% macro menu_link(href, text, target) %} ... {% endmacro menu_link %} ``` Then to be able to call it like this: ``` {% menu_link(href="/something", text="link", target="_blank") %} ``` It makes the code much better when reading it. As a first step, only allowing it for macros would be nice, but potentially extending it to filters would be nice too.
I worry that this would be a little foreign to users -- that is, I'm not sure it passes the design test of "it should be obvious how this gets compiled to Rust code". Does it really matter? If this is a big enough concern, we can add a new entry in the askama book explaining how it is generated. It matters to me -- I think an important design aspect of the templating language for Askama is that people can reason about how their template code gets translated into Rust code. Why don't you write the paragraph that explains this first and we can see how that looks? Sure. I'll do that (hopefully) soon. So now that #893 is merged, let's come back to this. :laughing: So I had in mind to keep a `Vec<String>` for each macro where each element is a macro argument name. Then when we encounter a macro with named arguments (should we allw to have a mix between named and not named?), we store the expression into a variable in the same order as declared in the template (so the "computation order" remains the same) and then pass the variables in the correct order to the macro. Does this sound like an acceptable approach?
2023-11-17T13:50:00Z
0.12
2023-11-28T10:54:25Z
4dab5f91ba15e7c238ddf6223ec7b45eef32cab4
[ "test_one_func", "test_one_func_binop", "test_one_func_self", "test_one_func_index", "test_coerce", "test_path_ext_html", "test_path_ext_html_and_ext_txt", "test_path_ext_html_jinja", "test_path_ext_html_jinja_and_ext_txt", "test_path_ext_jinja", "test_path_ext_jinja_and_ext_txt", "filter_esca...
[]
[]
[]
auto_2025-06-03
rinja-rs/askama
401
rinja-rs__askama-401
[ "333", "221", "107" ]
5057b75e7752f2186157fb3e1f5e5d2d0c5ff880
diff --git a/askama_shared/src/generator.rs b/askama_shared/src/generator.rs --- a/askama_shared/src/generator.rs +++ b/askama_shared/src/generator.rs @@ -667,8 +667,26 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { ", _loop_item) in ::askama::helpers::TemplateLoop::new({}) {{", expr_code )), + Expr::Array(..) => buf.writeln(&format!( + ", _loop_item) in ::askama::helpers::TemplateLoop::new({}.iter()) {{", + expr_code + )), + // If `iter` is a call then we assume it's something that returns + // an iterator. If not then the user can explicitly add the needed + // call without issues. + Expr::MethodCall(..) | Expr::PathCall(..) | Expr::Index(..) => buf.writeln(&format!( + ", _loop_item) in ::askama::helpers::TemplateLoop::new(({}).into_iter()) {{", + expr_code + )), + // If accessing `self` then it most likely needs to be + // borrowed, to prevent an attempt of moving. + _ if expr_code.starts_with("self.") => buf.writeln(&format!( + ", _loop_item) in ::askama::helpers::TemplateLoop::new(((&{}).into_iter())) {{", + expr_code + )), + // Otherwise, we borrow `iter` assuming that it implements `IntoIterator`. _ => buf.writeln(&format!( - ", _loop_item) in ::askama::helpers::TemplateLoop::new((&{}).into_iter()) {{", + ", _loop_item) in ::askama::helpers::TemplateLoop::new(({}).into_iter()) {{", expr_code )), }?;
diff --git a/testing/tests/loops.rs b/testing/tests/loops.rs --- a/testing/tests/loops.rs +++ b/testing/tests/loops.rs @@ -67,3 +67,39 @@ fn test_for_range() { "foo (first)\nfoo (last)\nbar\nbar\nfoo\nbar\nbar\n" ); } + +#[derive(Template)] +#[template(source = "{% for i in [1, 2, 3] %}{{ i }}{% endfor %}", ext = "txt")] +struct ForArrayTemplate {} + +#[test] +fn test_for_array() { + let t = ForArrayTemplate {}; + assert_eq!(t.render().unwrap(), "123"); +} + +#[derive(Template)] +#[template( + source = "{% for i in [1, 2, 3].iter() %}{{ i }}{% endfor %}", + ext = "txt" +)] +struct ForMethodCallTemplate {} + +#[test] +fn test_for_method_call() { + let t = ForMethodCallTemplate {}; + assert_eq!(t.render().unwrap(), "123"); +} + +#[derive(Template)] +#[template( + source = "{% for i in [1, 2, 3, 4, 5][3..] %}{{ i }}{% endfor %}", + ext = "txt" +)] +struct ForIndexTemplate {} + +#[test] +fn test_for_index() { + let t = ForIndexTemplate {}; + assert_eq!(t.render().unwrap(), "45"); +}
for-loop on values of a BTreeMap inside a template does not compile Hi Askama team, I'm hitting the an issue with for-loops inside template on `(some BTreeMap).values()`. ## Preliminary: what DOES work Consider first the following piece of code, which works, demonstrating that the `values()` function of `BTreeMap` can be used inside an Askama template, as expected: `main.rs`: ```rust use std::collections::BTreeMap; use askama::Template; #[derive(Debug)] struct Foo { foo: u64, } fn make_map() -> BTreeMap<u64, Foo> { let mut map : BTreeMap<u64, Foo> = BTreeMap::new(); map.insert(23, Foo { foo: 51} ); map } #[derive(Template)] #[template(path = "template.txt")] struct MyTemplate<'a> { map : &'a BTreeMap<u64, Foo> } fn main() { println!("Demo of weird stuff with BTreeMap in Askama template"); let map = make_map(); for foo in map.values() { println!("{:?}", foo) } let rendered = (MyTemplate { map : &map }).render().unwrap(); println!("{}", rendered); } ``` `template.txt`: ``` {{ map.values().count() }} ``` This works just fine, and the template renders the number of values, which is 1. ## But iterating does not work Now add the following to the template: ``` {% for foo in map.values() %} {{ format!("{:?}", foo) }} {% endfor %} ``` This won't compile: > move occurs because value has type `std::collections::btree_map::Values<'_, u64, Foo>`, which does not implement the `Copy` trait This surprises me, since in the main we also have a similar for-loop on the values, which work just fine. ## Workaround: collect references to values in a vector of references I did find the following workaround: in the `MyTemplate` struct, add field ```rust foos : &'a Vec<&'a Foo> ``` In `main.rs`, allocate a vector of references to the map values: ```rust let foos : Vec<& Foo> = map.values().collect(); ... MyTemplate { ..., foos : &foos }... ``` and iterate on `foos` in the template. This works, but is cumbersome. Thanks in advance for considering this report! Don't force adding "&" to start of collection for TemplateLoop Currently the TemplateLoop generator always appends `&` to every expression. This is inconvenient as it doesn't allow iteration over collections that are not owned by a struct but are passed by reference. For example today this does not work: welcome.rs ``` #[derive(Template)] #[template(path = "apps/welcome/welcome.html")] struct Landing<'a> { locales: &'a HashMap<String, Locale>, } pub fn index(req: HttpRequest<AppState>) -> Result<HttpResponse, Error> { let locales = &req.state().locales; let landing = Landing { locales: locales, }; landing.respond_to(&req) } ``` welcome.html ``` <h1>Welcome!</h1> <div> {% for locale in locales.values() %} <p> <a hreflang="{{ locale.key }}" href="/{{ locale.key }}/">{{ locale.description }}</a> </p> {% endfor %} </div> ``` This code will produce a cannot move out of borrowed context error. The current work around is: welcome.rs ``` #[derive(Template)] #[template(path = "apps/welcome/welcome.html", print = "all")] struct Landing<'a> { locales: &'a HashMap<String, Locale>, } // TODO: Delete after upgrading askama struct LocaleAskama<'a> { description: &'a str, key: &'a str, } pub fn index(req: HttpRequest<AppState>) -> Result<HttpResponse, Error> { let locales = &req.state().locales; let mut locales_parsed = Vec::<LocaleAskama>::new(); for locale in locales.values() { locales_parsed.push(LocaleAskama{ description: locale.description.as_str(), key: locale.key.as_str(), }); } let landing = Landing { locales: locales_parsed, }; landing.respond_to(&req) } ``` The bad thing is that this would be a breaking change as it would require collections that are owned by the template to have the & prefix. I think this should be the correct pattern, I couldn't figure out any other way to check of the template field was a reference or owned. Also, I noticed there is no CHANGELOG.md file, I can create one if you think it's a good idea. Cannot move out of borrowed content in for loop Hi there, I am probably not posting this in the right place but I seek help using this library. I am trying to iterate over a list of x509Name's using the following code in my template : ```rust {% for entry in certificate.subject_name().entries() %} {% endfor %} ``` `certificate` being an instance of [X509](https://docs.rs/openssl/0.10.11/x86_64-unknown-linux-gnu/openssl/x509/struct.X509.html). I have the following error : `cannot move out of borrowed content`. I am pretty new to rust, this must be something easy but I have not yet full comprehension of the concept of ownership..
Allocating a `Vec` just to appease `djc/askama` seems unfortunate. I wonder whether adding something like the `&`-syntax could improve things: ``` {% for &foo in map.values() %} ``` I encountered the same issue trying to iterate over a `BTreeMap` using `.rev()`: ```jinja {% for (date, day_videos) in videos.videos %} ``` compiles successfully into: ```rust for ((date,day_videos,), _loop_item) in ::askama::helpers::TemplateLoop::new((&self.videos.videos).into_iter()) { ``` Whereas ```jinja {% for (date, day_videos) in videos.videos.into_iter().rev() %} ``` compiles with error to ```rust for ((date,day_videos,), _loop_item) in ::askama::helpers::TemplateLoop::new((&self.videos.videos.into_iter().rev()).into_iter()) { ``` This results in a similar error: ``` error[E0507]: cannot move out of `self.videos.videos` which is behind a shared reference ... move occurs because `self.videos.videos` has type `std::collections::BTreeMap<std::string::String, std::vec::Vec<web::WebVideoInfo<'_>>>`, which does not implement the `Copy` trait ``` Can you try with `videos.videos.iter().rev()`? Similar error: ```jinja {% for (date, day_videos) in videos.videos.iter().rev() %} ``` becomes ```rust for ((date,day_videos,), _loop_item) in ::askama::helpers::TemplateLoop::new((&self.videos.videos.iter().rev()).into_iter()) { ``` resulting in: ```rust error[E0507]: cannot move out of a shared reference --> src/web.rs:177:10 | 177 | #[derive(Template)] | ^^^^^^^^ move occurs because value has type `std::iter::Rev<std::collections::btree_map::Iter<'_, std::string::String, std::vec::Vec<web::WebVideoInfo<'_>>>>`, which does not implement the `Copy` trait ``` @djc, any update on this? Do you know why it's happening? Do you have some solution in mind? How does it rank on your priority list? It's pretty high on my priority list, but I'm currently on holiday so not doing a ton of open source work. I think I may have a solution in find, but it might not be fully backwards compatible, so I need to think about it more. Thanks @djc for the update! There's actually a fairly extensive change log here: https://github.com/djc/askama/releases, but maybe it would help to link to it from the README to make it more discoverable? Although I agree that this should work, I don't think this is the right direction for a solution. Can you show in more detail what causes the "cannot move out of borrowed context" problem in this case? Great, I'll update https://github.com/djc/askama/releases . Definitely not sure if this is the right solution either but will be great to be able to use referenced collections. When I use 0.8 Askama here is what I get: Code: ``` #[derive(Template)] #[template(path = "apps/welcome/welcome.html", print = "all")] struct Landing<'a> { locales: &'a HashMap<String, Locale>, } pub fn index(req: HttpRequest<AppState>) -> Result<HttpResponse, Error> { let locales = &req.state().locales; let landing = Landing { locales: locales, }; landing.respond_to(&req) } ``` Template ``` <h1>Welcome!</h1> <div> {% for locale in locales.values() %} <p> <a hreflang="{{ locale.key }}" href="/{{ locale.key }}/">{{ locale.description }}</a> </p> {% endfor %} </div> ``` Askama Output ``` [Lit("", "<h1>Welcome!</h1>\r\n<div>", "\r\n "), Loop(WS(false, false), Name("locale"), MethodCall(Var("locales"), "values", []), [Lit("\r\n ", "<p>\r\n <a hreflang=\"", ""), Expr(WS(false, false), Attr(Var("locale"), "key")), Lit("", "\" href=\"/", ""), Expr(WS(false, false), Attr(Var("locale"), "key")), Lit("", "/\">", ""), Expr(WS(false, false), Attr(Var("locale"), "description")), Lit("", "</a>\r\n </p>", "\r\n ")], WS(false, false)), Lit("\r\n", "</div>", "")] impl < 'a > ::askama::Template for Landing< 'a > { fn render_into(&self, writer: &mut ::std::fmt::Write) -> ::askama::Result<()> { include_bytes ! ( "C:\\Users\\GregElenbaas\\workspace\\walkwiki\\templates\\apps/welcome/welcome.html" ) ; writer.write_str("<h1>Welcome!</h1>\r\n<div>\r\n ")?; for (locale, _loop_item) in ::askama::helpers::TemplateLoop::new((&self.locales.values()).into_iter()) { write!( writer, "\r\n <p>\r\n <a hreflang=\"{expr0}\" href=\"/{expr0}/\">{expr1}</a>\r\n </p>\r\n ", expr0 = &::askama::MarkupDisplay::new_unsafe(&locale.key, ::askama::Html), expr1 = &::askama::MarkupDisplay::new_unsafe(&locale.description, ::askama::Html), )?; } writer.write_str("\r\n</div>")?; Ok(()) } fn extension() -> Option<&'static str> { Some("html") } fn size_hint() -> usize { 8 } } impl < 'a > ::std::fmt::Display for Landing< 'a > { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { ::askama::Template::render_into(self, f).map_err(|_| ::std::fmt::Error {}) } } impl < 'a > ::askama::actix_web::Responder for Landing< 'a > { type Item = ::askama::actix_web::HttpResponse; type Error = ::askama::actix_web::Error; fn respond_to<S>(self, _req: &::askama::actix_web::HttpRequest<S>) -> ::std::result::Result<Self::Item, Self::Error> { use ::askama::actix_web::TemplateIntoResponse; self.into_response() } ``` Compiler Error ``` error[E0507]: cannot move out of borrowed content --> src\apps\welcome\mod.rs:11:10 | 11 | #[derive(Template)] | ^^^^^^^^ cannot move out of borrowed content error: aborting due to previous error For more information about this error, try `rustc --explain E0507`. error: Could not compile `walkwiki`. To learn more, run the command again with --verbose. ``` So now can you put the generated source code in your own source code, comment out the `derive` and `template` attributes so that we can see the precise error the compiler generates? Sure, here you go. Code: ``` struct Landing<'a> { base: BaseTemplateData<'a>, locales: &'a HashMap<String, Locale>, } impl < 'a > ::askama::Template for Landing< 'a > { fn render_into(&self, writer: &mut ::std::fmt::Write) -> ::askama::Result<()> { include_bytes ! ( "C:\\Users\\GregElenbaas\\workspace\\walkwiki\\templates\\apps/welcome/welcome.html" ) ; writer.write_str("<div>\r\n ")?; for (locale, _loop_item) in ::askama::helpers::TemplateLoop::new((&self.locales.values()).into_iter()) { write!( writer, "\r\n <p>\r\n <a hreflang=\"{expr0}\" href=\"/{expr0}/\">{expr1}</a>\r\n </p>\r\n ", expr0 = &::askama::MarkupDisplay::new_unsafe(&locale.key, ::askama::Html), expr1 = &::askama::MarkupDisplay::new_unsafe(&locale.description, ::askama::Html), )?; } writer.write_str("\r\n</div>")?; Ok(()) } fn extension() -> Option<&'static str> { Some("html") } fn size_hint() -> usize { 8 } } impl < 'a > ::std::fmt::Display for Landing< 'a > { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { ::askama::Template::render_into(self, f).map_err(|_| ::std::fmt::Error {}) } } impl < 'a > ::askama::actix_web::Responder for Landing< 'a > { type Item = ::askama::actix_web::HttpResponse; type Error = ::askama::actix_web::Error; fn respond_to<S>(self, _req: &::askama::actix_web::HttpRequest<S>) -> ::std::result::Result<Self::Item, Self::Error> { use ::askama::actix_web::TemplateIntoResponse; self.into_response() } } pub fn index(req: HttpRequest<AppState>) -> Result<HttpResponse, Error> { let locales = &req.state().locales; let component_locales = &req.state().component_locales; let landing = Landing { base: BaseTemplateData { app: &component_locales["en"]["land"], chrome: &component_locales["en"]["chrm"], body_class: "welcome-page", href_langs: Vec::new(), page_lang: &"x-default".to_string(), style_sheet: &req.state().style_sheet, }, locales: locales, }; landing.respond_to(&req) } ``` Error: ``` error[E0507]: cannot move out of borrowed content --> src\apps\welcome\mod.rs:29:74 | 29 | for (locale, _loop_item) in ::askama::helpers::TemplateLoop::new((&self.locales.values()).into_iter()) { | ^^^^^^^^^^^^^^^^^^^^^^^^ cannot move out of borrowed content error: aborting due to previous error For more information about this error, try `rustc --explain E0507`. error: Could not compile `walkwiki`. To learn more, run the command again with --verbose. ``` Just checking @djc if you had any feedback I suppose the problem here is that you want `(&self.locales).values()` but you're getting `&self.locales.values()` which is different in terms of ownership? So far I've resisted adding `&` in the template language, and I don't like the idea of adding it. But right now I don't have any good ideas for workarounds for your problem. I understand not wanting to have to think about "&" in Askama templates. The issue is that I have some long lived collections of strings that are loaded at server start that are used to populate the text for various templates. Askama currently can't loop through collections held by the template struct that are references with lifetime annotations, and not owned by the struct itself. This PR fixes that issue but is breaking. I've been trying to research a way in Rust that we could detect a value is a reference instead of owned at run time. I am going to look into TryFrom but am not sure if that's the right way to go. I wonder what we could do here if we add filters to the mix. That way, you could at least write Rust code that adapts your iterator, in Rust code, possibly to some trait defined in askama that doesn't get the mandatory reference treatment. Does that make sense? My issue with the current implementation is that it seems `into_iter()` only happens to work with types like `Vec` due to [its implementation under the hood](https://doc.rust-lang.org/src/alloc/vec.rs.html#1876-1883) which actually uses `iter()`. Conversely, I get the rational behind this and it's definitely a nice idea to not mutate iterables used in templates. However, I think that trying to implement `for` loops in a different way to how Rust does will ultimately always cause conflict with the language and confusion for users of this library. It would be great to get this resolved because, at least for me, it currently presents quite a barrier to using Askama 😞 This is a fine place to post this! So Askama's `Template` trait takes a reference to your context struct and in general converts everything in the template code to references in order to make things work. It's possible that that doesn't work in this case. As a first step, try enabling the `print = "code"` attribute on the `template()` call, so you can see the generated code, then paste that generated code into your source file and comment out the derive call and related `template()` attribute. That should pinpoint to the exact location of the error. If you then paste the generated code here, I can also take another look and see if the code generator can be improved in this respect. Thanks for your answer, Rust community is not a lie :) I tried the `print` attribute as suggested and the following code was generated : ```rust match &self.certificate { Some(cert) => { for (_loop_index, entry) in (&cert.subject_name().entries()).into_iter().enumerate() { writer.write_str("\n\n ")?; } } None => { writer.write_str("\n ")?; } } ``` Removing the leading `&` solves the problem but I have no idea how to do this in Jinja like code. You can try doing it like this: ``` {% let entries = cert.subject_name().entries() %} {% for entry in entries %} {% endfor %} ``` But I'm not sure it'll work... In general, you cannot remove the `&` in the template code. Tried that as well, same error. `cannot move out of borrowed content`. My current work-around is creating a structure and extracting data in controller before rendering in the template. I think that's probably the best workaround for now. :+1: I am also running into this issue. My code is trying to create an iterator in the template: ``` {% for i in 1..n %} {% endfor %} ``` Just wanted to follow-up on this issue with a similar problem. Given the following structs: ```rust pub struct Coursework { pub instructor: String, pub name: String, pub semester: String, pub short: String, } #[derive(Debug, Template)] #[template(path = "markdown/courses.md", print = "code")] pub struct MarkdownCoursesTemplate { pub coursework: Vec<Coursework>, } ``` and the following template ```md ## Coursework <table class="table table-hover"> {% for course in coursework %} <tr> <td class='col-md-1'>{{ course.semester }}</td> <td><strong>{{ course.name }}</strong> ({{ course.short }}), {{ course.instructor }}</td> </tr> {% endfor %} </table> ``` The generated code is ```rust impl ::askama::Template for MarkdownCoursesTemplate { fn render_into(&self, writer: &mut ::std::fmt::Write) -> ::askama::Result<()> { writer.write_str("## Coursework\n\n<table class=\"table table-hover\">")?; writer.write_str("\n")?; for (_loop_index, course) in (&self.coursework).into_iter().enumerate() { writer.write_str("\n")?; writer.write_str("<tr>\n <td class=\'col-md-1\'>")?; write!(writer, "{}", &{ course.semester })?; writer.write_str("</td>\n <td><strong>")?; write!(writer, "{}", &{ course.name })?; writer.write_str("</strong> (")?; write!(writer, "{}", &{ course.short })?; writer.write_str("),")?; writer.write_str(" ")?; write!(writer, "{}", &{ course.instructor })?; writer.write_str("</td>\n</tr>")?; writer.write_str("\n")?; } writer.write_str("\n")?; writer.write_str("</table>")?; Ok(()) } fn extension(&self) -> Option<&str> { Some("md") } } ``` This fails compilation with ``` error[E0507]: cannot move out of borrowed content --> src/markdown.rs:17:37 | 17 | write!(writer, "{}", &{ course.semester })?; | ^^^^^^ cannot move out of borrowed content error[E0507]: cannot move out of borrowed content --> src/markdown.rs:19:37 | 19 | write!(writer, "{}", &{ course.name })?; | ^^^^^^ cannot move out of borrowed content error[E0507]: cannot move out of borrowed content --> src/markdown.rs:21:37 | 21 | write!(writer, "{}", &{ course.short })?; | ^^^^^^ cannot move out of borrowed content error[E0507]: cannot move out of borrowed content --> src/markdown.rs:24:37 | 24 | write!(writer, "{}", &{ course.instructor })?; | ^^^^^^ cannot move out of borrowed content error: aborting due to 4 previous errors ``` because of `course` being moved into the `&{ course._ }` block. Had the generated code been ```rust impl ::askama::Template for MarkdownCVTemplate { fn render_into(&self, writer: &mut ::std::fmt::Write) -> ::askama::Result<()> { writer.write_str("## Coursework\n\n<table class=\"table table-hover\">")?; writer.write_str("\n")?; for (_loop_index, course) in (&self.coursework).into_iter().enumerate() { writer.write_str("\n")?; writer.write_str("<tr>\n <td class=\'col-md-1\'>")?; write!(writer, "{}", course.semester)?; // <-- writer.write_str("</td>\n <td><strong>")?; write!(writer, "{}", course.name)?; // <-- writer.write_str("</strong> (")?; write!(writer, "{}", course.short)?; // <-- writer.write_str("),")?; writer.write_str(" ")?; write!(writer, "{}", course.instructor)?; // <-- writer.write_str("</td>\n</tr>")?; writer.write_str("\n")?; } writer.write_str("\n")?; writer.write_str("</table>")?; Ok(()) } fn extension(&self) -> Option<&str> { Some("md") } } ``` it would have compiled and I believe would have worked as I expected. Coming from using Jinja in Python, I suspect that there is way to structure my code such that this works. Is there a recommended workaround for this type of scenario? Must these variables be copyable? @lukehsiao I think that is essentially the problem from #132, can you comment there and try the suggested fix? @djc: what's the purpose of `_loop_item`? It doesn't seem to be even accessible from template code. I know very little about askama internals, so there must be a good reason not to translate loops to just loops, what is it? They are translated to just loops. `_loop_item` is accessible to templates as `loop.index` and friends. The reason for this issue (IIRC) is that `Template::render()` by design only takes an immutable reference of the context type. I designed it this way so that eventually it might be possible to render a single instance multiple times (for something like functional reactive UIs), and conceptually it seems sensible to me that the act of rendering a template ought not to mutate the object it renders from. Actually, this is not quite the case. If the purpose of `_loop_item` is just to supply what it's supplying, then this could be as well achieved by the user with `for (i, y) in x.iter().enumerate()`. This doesn't mutate the template (I agree with you on that), but it creates a mutable iterator. At the moment, the example above fails because `x` means `self.x`, and that is moved to the iterator. How about the simpler translation where you don't prefix all variables with `self` (let the user do that, I'm sure they can figure it out), and translate constructs more directly? Why does this fail? In my example above, I would write `for (i, y) in self.x.iter().enumerate()`, and that would get copy-pasted directly without any parsing or modification. This would let the Rust compiler tell me about parsing errors. Because that adds a bunch of boiler plate for the common case. I don't have the exact issue here paged in at the moment and it sounds like you do, so maybe you can explain in more detail why your `self.x.iter()` would work? (You could write `self.x.iter()` for the loop expression today, IIRC, and the code generated around that should not cause it to fail compilation in my head at least, but as I said, I don't remember the subtleties here right now.) This is because, AFAICT, in the current implementation `self.x` seems to be moved to the `askama::helpers::TemplateLoop` iterator, because of a syntax issue. I don't have much more detail, as `rustc` doesn't provide more (which I totally understand at this stage of development of Askama, and with the current maturity of code generation in Rust). However, `for y in self.x.iter()` just borrows `self.x`, so that wouldn't be a problem. > Because that adds a bunch of boiler plate for the common case. I'm not sure about that, since it just adds a `self`. I can see how the simple examples in the README would look a bit longer with the extra `self`, but given how I've been using Askama (I'm trying to convert https://nest.pijul.com, it's already partially served by Askama), my common case when writing code would be greatly simplified if the syntax was just Rust, since I wouldn't have to look at generated code to figure out how my code was translated, why things were moved/mutated, etc. Also, doing less translation would give you the extra benefit of generating Rust code with the correct source positions, resulting in nicer error messages. You can try to add `print = "code"` to the `#[template()]` attribute, compile it, copy the generated code from the terminal back into your source to get a better error message. If you can then suggest alternative code generation techniques that yield better results, that would be great! Sorry, I'm not going to change the syntax to always require `self`. Another example use case which breaks: Types with multiple iterators yielding different types of iterators have to be disambiguated by type annotation which is not possible afaik ```rust struct Z{ children: Vec<Vec<u8>>, } impl Z { pub fn iter_vec() -> { unimplemented!()} pub fn iter_items() -> { unimplemented!()} } ``` `IntoIterator` can only be implemented for one of those, for the other the above is true and so far I had to resort to iterating by using indices. I think this is related to #221 I think we could fix this by using [autoref-based specialization](https://lukaskalbertodt.github.io/2019/12/05/generalized-autoref-based-specialization.html) to dispatch to proper handling in Askama. If someone wants to take a whack at implementing this, I'd be happy to provide further guidance and review!
2020-12-15T06:21:33Z
0.10
2021-02-18T12:18:18Z
49252d2457f280026c020d0df46733578eb959a5
[ "test_for", "test_for_range", "test_precedence_for", "test_nested_for" ]
[]
[]
[]
auto_2025-06-03
rinja-rs/askama
399
rinja-rs__askama-399
[ "397", "397" ]
5b01e605914a49f0b9e71e7dbe7c17ef1de2c522
diff --git a/askama_shared/src/generator.rs b/askama_shared/src/generator.rs --- a/askama_shared/src/generator.rs +++ b/askama_shared/src/generator.rs @@ -444,8 +444,8 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { Node::Cond(ref conds, ws) => { self.write_cond(ctx, buf, conds, ws)?; } - Node::Match(ws1, ref expr, inter, ref arms, ws2) => { - self.write_match(ctx, buf, ws1, expr, inter, arms, ws2)?; + Node::Match(ws1, ref expr, ref arms, ws2) => { + self.write_match(ctx, buf, ws1, expr, arms, ws2)?; } Node::Loop(ws1, ref var, ref iter, ref body, ws2) => { self.write_loop(ctx, buf, ws1, var, iter, body, ws2)?; diff --git a/askama_shared/src/generator.rs b/askama_shared/src/generator.rs --- a/askama_shared/src/generator.rs +++ b/askama_shared/src/generator.rs @@ -561,23 +561,28 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { buf: &mut Buffer, ws1: WS, expr: &Expr, - inter: Option<&'a str>, arms: &'a [When], ws2: WS, ) -> Result<usize, CompileError> { self.flush_ws(ws1); let flushed = self.write_buf_writable(buf)?; let mut arm_sizes = Vec::new(); - if let Some(inter) = inter { - if !inter.is_empty() { - self.next_ws = Some(inter); - } - } let expr_code = self.visit_expr_root(expr)?; buf.writeln(&format!("match &{} {{", expr_code))?; - for arm in arms { + + let mut arm_size = 0; + for (i, arm) in arms.iter().enumerate() { let &(ws, ref variant, ref params, ref body) = arm; + self.handle_ws(ws); + + if i > 0 { + arm_sizes.push(arm_size + self.write_buf_writable(buf)?); + + buf.writeln("}")?; + self.locals.pop(); + } + self.locals.push(); match *variant { Some(ref param) => { diff --git a/askama_shared/src/generator.rs b/askama_shared/src/generator.rs --- a/askama_shared/src/generator.rs +++ b/askama_shared/src/generator.rs @@ -624,15 +629,17 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { } } buf.writeln(" => {")?; - self.handle_ws(ws); - let arm_size = self.handle(ctx, body, buf, AstLevel::Nested)?; - arm_sizes.push(arm_size + self.write_buf_writable(buf)?); - buf.writeln("}")?; - self.locals.pop(); + + arm_size = self.handle(ctx, body, buf, AstLevel::Nested)?; } - buf.writeln("}")?; self.handle_ws(ws2); + arm_sizes.push(arm_size + self.write_buf_writable(buf)?); + buf.writeln("}")?; + self.locals.pop(); + + buf.writeln("}")?; + Ok(flushed + median(&mut arm_sizes)) } diff --git a/askama_shared/src/heritage.rs b/askama_shared/src/heritage.rs --- a/askama_shared/src/heritage.rs +++ b/askama_shared/src/heritage.rs @@ -89,7 +89,7 @@ impl<'a> Context<'a> { Node::Loop(_, _, _, nodes, _) => { nested.push(nodes); } - Node::Match(_, _, _, arms, _) => { + Node::Match(_, _, arms, _) => { for (_, _, _, arm) in arms { nested.push(arm); } diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -19,7 +19,7 @@ pub enum Node<'a> { LetDecl(WS, Target<'a>), Let(WS, Target<'a>, Expr<'a>), Cond(Vec<(WS, Option<Expr<'a>>, Vec<Node<'a>>)>, WS), - Match(WS, Expr<'a>, Option<&'a str>, Vec<When<'a>>, WS), + Match(WS, Expr<'a>, Vec<When<'a>>, WS), Loop(WS, Target<'a>, Expr<'a>, Vec<Node<'a>>, WS), Extends(Expr<'a>), BlockDef(WS, &'a str, Vec<Node<'a>>, WS), diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -771,8 +771,8 @@ fn block_match<'a>(i: &'a [u8], s: &'a Syntax<'a>) -> IResult<&'a [u8], Node<'a> arms.push(arm); } - let inter = match inter { - Some(Node::Lit(lws, val, rws)) => { + match inter { + Some(Node::Lit(_, val, rws)) => { assert!( val.is_empty(), "only whitespace allowed between match and first when, found {}", diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -783,18 +783,16 @@ fn block_match<'a>(i: &'a [u8], s: &'a Syntax<'a>) -> IResult<&'a [u8], Node<'a> "only whitespace allowed between match and first when, found {}", rws ); - Some(lws) } - None => None, + None => {} _ => panic!("only literals allowed between match and first when"), - }; + } Ok(( i, Node::Match( WS(pws1.is_some(), nws1.is_some()), expr, - inter, arms, WS(pws2.is_some(), nws2.is_some()), ),
diff --git a/testing/tests/gen_ws_tests.py b/testing/tests/gen_ws_tests.py --- a/testing/tests/gen_ws_tests.py +++ b/testing/tests/gen_ws_tests.py @@ -4,12 +4,23 @@ from itertools import product, chain, zip_longest, tee +# The amount of branches to generate +BRANCHES = 2 # branches + IF, ELSE_IF, ELSE, END_IF = 0, 1, 2, 3 NL = "\\n" dash = lambda ws: [" ", "-"][ws] +def trim(s, ws): + if ws[0]: + s = s.lstrip() + if ws[1]: + s = s.rstrip() + return s + + def cond_kind(i, n): i += 1 if i == 1: diff --git a/testing/tests/gen_ws_tests.py b/testing/tests/gen_ws_tests.py --- a/testing/tests/gen_ws_tests.py +++ b/testing/tests/gen_ws_tests.py @@ -71,17 +82,35 @@ def write_cond(conds, active_branch): return code, expected -if __name__ == "__main__": - # The amount of branches to generate - n = 2 # branches +def write_match(contents, arms, match_ws): + before, expr, after = contents + code = before + pws, nws = match_ws[0] + code += f"{{%{dash(pws)} match {expr} {dash(nws)}%}}" + + for (arm, expr), (pws, nws) in zip(arms, match_ws[1:-1]): + code += f"{{%{dash(pws)} when {arm} {dash(nws)}%}}{expr}" + + pws, nws = match_ws[-1] + code += f"{{%{dash(pws)} endmatch {dash(nws)}%}}" + code += after + + return code - with open("ws.rs", "w") as f: - f.write("""\ -// This file is auto generated by gen_ws_tests.py -use askama::Template; +def write_match_result(active_arm, contents, arms, match_ws): + before, expr, after = contents + expected = "" + expected += trim(before, (False, match_ws[0][0])) + expected += trim(arms[active_arm][1], (match_ws[1:][active_arm][1], match_ws[1:][active_arm+1][0])) + expected += trim(after, (match_ws[-1][1], False)) + return expected + + +def write_cond_tests(f): + f.write(""" macro_rules! test_template { ($source:literal, $rendered:expr) => {{ #[derive(Template)] diff --git a/testing/tests/gen_ws_tests.py b/testing/tests/gen_ws_tests.py --- a/testing/tests/gen_ws_tests.py +++ b/testing/tests/gen_ws_tests.py @@ -97,16 +126,61 @@ def write_cond(conds, active_branch): fn test_cond_ws() { """) - for branches in range(1, n + 1): - for x in product([False, True], repeat=(branches+1)*2): - # it = iter(x) - # conds = list(zip(it, it)) - conds = list(zip(x[::2], x[1::2])) + for branches in range(1, BRANCHES + 1): + for x in product([False, True], repeat=(branches+1)*2): + # it = iter(x) + # conds = list(zip(it, it)) + conds = list(zip(x[::2], x[1::2])) + + for i in range(branches): + code, expected = write_cond(conds, i) + f.write(f' test_template!("{code}", "{expected}");\n') + + if branches != BRANCHES: + f.write("\n") + f.write("}\n") - for i in range(branches): - code, expected = write_cond(conds, i) - f.write(f' test_template!("{code}", "{expected}");\n') - if branches != n: - f.write("\n") - f.write("}\n") +def write_match_tests(f): + f.write(""" +#[rustfmt::skip] +macro_rules! test_match { + ($source:literal, $some_rendered:expr, $none_rendered:expr) => {{ + #[derive(Template)] + #[template(source = $source, ext = "txt")] + struct MatchWS { + item: Option<&'static str>, + } + + assert_eq!(MatchWS { item: Some("foo") }.render().unwrap(), $some_rendered); + assert_eq!(MatchWS { item: None }.render().unwrap(), $none_rendered); + }}; +} + +#[rustfmt::skip] +#[test] +fn test_match_ws() { +""") + + contents = "before ", "item", " after" + arms = [("Some with (item)", " foo "), ("None", " bar ")] + + for x in product([False, True], repeat=len(arms)*2+1): + x = [False, False, *x, False] + arms_ws = list(zip(x[::2], x[1::2])) + + code = write_match(contents, arms, arms_ws) + some_expected = write_match_result(0, contents, arms, arms_ws) + none_expected = write_match_result(1, contents, arms, arms_ws) + + f.write(f' test_match!("{code}", "{some_expected}", "{none_expected}");\n') + + f.write("}\n") + + +if __name__ == "__main__": + with open("ws.rs", "w") as f: + f.write("// This file is auto generated by gen_ws_tests.py\n\n") + f.write("use askama::Template;\n") + write_cond_tests(f) + write_match_tests(f) diff --git a/testing/tests/matches.rs b/testing/tests/matches.rs --- a/testing/tests/matches.rs +++ b/testing/tests/matches.rs @@ -17,19 +17,19 @@ struct MatchOptRefTemplate<'a> { #[test] fn test_match_option() { let s = MatchOptTemplate { item: Some("foo") }; - assert_eq!(s.render().unwrap(), "\n\nFound literal foo\n"); + assert_eq!(s.render().unwrap(), "\nFound literal foo\n"); let s = MatchOptTemplate { item: Some("bar") }; - assert_eq!(s.render().unwrap(), "\n\nFound bar\n"); + assert_eq!(s.render().unwrap(), "\nFound bar\n"); let s = MatchOptTemplate { item: None }; - assert_eq!(s.render().unwrap(), "\n\nNot Found\n"); + assert_eq!(s.render().unwrap(), "\nNot Found\n"); } #[test] fn test_match_ref_deref() { let s = MatchOptRefTemplate { item: &Some("foo") }; - assert_eq!(s.render().unwrap(), "\n\nFound literal foo\n"); + assert_eq!(s.render().unwrap(), "\nFound literal foo\n"); } #[derive(Template)] diff --git a/testing/tests/matches.rs b/testing/tests/matches.rs --- a/testing/tests/matches.rs +++ b/testing/tests/matches.rs @@ -41,10 +41,10 @@ struct MatchLitTemplate<'a> { #[test] fn test_match_literal() { let s = MatchLitTemplate { item: "bar" }; - assert_eq!(s.render().unwrap(), "\n\nFound literal bar\n"); + assert_eq!(s.render().unwrap(), "\nFound literal bar\n"); let s = MatchLitTemplate { item: "qux" }; - assert_eq!(s.render().unwrap(), "\n\nElse found qux\n"); + assert_eq!(s.render().unwrap(), "\nElse found qux\n"); } #[derive(Template)] diff --git a/testing/tests/matches.rs b/testing/tests/matches.rs --- a/testing/tests/matches.rs +++ b/testing/tests/matches.rs @@ -56,10 +56,10 @@ struct MatchLitCharTemplate { #[test] fn test_match_literal_char() { let s = MatchLitCharTemplate { item: 'b' }; - assert_eq!(s.render().unwrap(), "\n\nFound literal b\n"); + assert_eq!(s.render().unwrap(), "\nFound literal b\n"); let s = MatchLitCharTemplate { item: 'c' }; - assert_eq!(s.render().unwrap(), "\n\nElse found c\n"); + assert_eq!(s.render().unwrap(), "\nElse found c\n"); } #[derive(Template)] diff --git a/testing/tests/matches.rs b/testing/tests/matches.rs --- a/testing/tests/matches.rs +++ b/testing/tests/matches.rs @@ -71,10 +71,10 @@ struct MatchLitNumTemplate { #[test] fn test_match_literal_num() { let s = MatchLitNumTemplate { item: 42 }; - assert_eq!(s.render().unwrap(), "\n\nFound answer to everything\n"); + assert_eq!(s.render().unwrap(), "\nFound answer to everything\n"); let s = MatchLitNumTemplate { item: 23 }; - assert_eq!(s.render().unwrap(), "\n\nElse found 23\n"); + assert_eq!(s.render().unwrap(), "\nElse found 23\n"); } #[allow(dead_code)] diff --git a/testing/tests/matches.rs b/testing/tests/matches.rs --- a/testing/tests/matches.rs +++ b/testing/tests/matches.rs @@ -99,7 +99,7 @@ fn test_match_custom_enum() { b: 255, }, }; - assert_eq!(s.render().unwrap(), "\n\nColorful: #A000FF\n"); + assert_eq!(s.render().unwrap(), "\nColorful: #A000FF\n"); } #[derive(Template)] diff --git a/testing/tests/whitespace.rs b/testing/tests/whitespace.rs --- a/testing/tests/whitespace.rs +++ b/testing/tests/whitespace.rs @@ -37,5 +37,5 @@ fn test_extra_whitespace() { let mut template = AllowWhitespaces::default(); template.nested_1.nested_2.array = &["a0", "a1", "a2", "a3"]; template.nested_1.nested_2.hash.insert("key", "value"); - assert_eq!(template.render().unwrap(), "\n0\n0\n0\n0\n\n\n\n0\n0\n0\n0\n0\n\na0\na1\nvalue\n\n\n\n\n\n[\n \"a0\",\n \"a1\",\n \"a2\",\n \"a3\"\n]\n[\n \"a0\",\n \"a1\",\n \"a2\",\n \"a3\"\n][\n \"a0\",\n \"a1\",\n \"a2\",\n \"a3\"\n]\n[\n \"a1\"\n][\n \"a1\"\n]\n[\n \"a1\",\n \"a2\"\n][\n \"a1\",\n \"a2\"\n]\n[\n \"a1\"\n][\n \"a1\"\n]1-1-1\n3333 3\n2222 2\n0000 0\n3333 3\n\ntruefalse\nfalsefalsefalse\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); + assert_eq!(template.render().unwrap(), "\n0\n0\n0\n0\n\n\n\n0\n0\n0\n0\n0\n\na0\na1\nvalue\n\n\n\n\n\n[\n \"a0\",\n \"a1\",\n \"a2\",\n \"a3\"\n]\n[\n \"a0\",\n \"a1\",\n \"a2\",\n \"a3\"\n][\n \"a0\",\n \"a1\",\n \"a2\",\n \"a3\"\n]\n[\n \"a1\"\n][\n \"a1\"\n]\n[\n \"a1\",\n \"a2\"\n][\n \"a1\",\n \"a2\"\n]\n[\n \"a1\"\n][\n \"a1\"\n]1-1-1\n3333 3\n2222 2\n0000 0\n3333 3\n\ntruefalse\nfalsefalsefalse\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); } diff --git a/testing/tests/ws.rs b/testing/tests/ws.rs --- a/testing/tests/ws.rs +++ b/testing/tests/ws.rs @@ -161,3 +161,54 @@ fn test_cond_ws() { test_template!("\n1\r\n{%- if true -%}\n\n2\r\n\r\n{%- else -%}\n\n\n3\r\n\r\n\r\n{%- endif -%}\n\n\n\n4\r\n\r\n\r\n\r\n", "\n124"); test_template!("\n1\r\n{%- if false -%}\n\n2\r\n\r\n{%- else -%}\n\n\n3\r\n\r\n\r\n{%- endif -%}\n\n\n\n4\r\n\r\n\r\n\r\n", "\n134"); } + +#[rustfmt::skip] +macro_rules! test_match { + ($source:literal, $some_rendered:expr, $none_rendered:expr) => {{ + #[derive(Template)] + #[template(source = $source, ext = "txt")] + struct MatchWS { + item: Option<&'static str>, + } + + assert_eq!(MatchWS { item: Some("foo") }.render().unwrap(), $some_rendered); + assert_eq!(MatchWS { item: None }.render().unwrap(), $none_rendered); + }}; +} + +#[rustfmt::skip] +#[test] +fn test_match_ws() { + test_match!("before {% match item %}{% when Some with (item) %} foo {% when None %} bar {% endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{% when Some with (item) %} foo {% when None %} bar {%- endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{% when Some with (item) %} foo {% when None -%} bar {% endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{% when Some with (item) %} foo {% when None -%} bar {%- endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{% when Some with (item) %} foo {%- when None %} bar {% endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{% when Some with (item) %} foo {%- when None %} bar {%- endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{% when Some with (item) %} foo {%- when None -%} bar {% endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{% when Some with (item) %} foo {%- when None -%} bar {%- endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{% when Some with (item) -%} foo {% when None %} bar {% endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{% when Some with (item) -%} foo {% when None %} bar {%- endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{% when Some with (item) -%} foo {% when None -%} bar {% endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{% when Some with (item) -%} foo {% when None -%} bar {%- endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{% when Some with (item) -%} foo {%- when None %} bar {% endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{% when Some with (item) -%} foo {%- when None %} bar {%- endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{% when Some with (item) -%} foo {%- when None -%} bar {% endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{% when Some with (item) -%} foo {%- when None -%} bar {%- endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{%- when Some with (item) %} foo {% when None %} bar {% endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{%- when Some with (item) %} foo {% when None %} bar {%- endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{%- when Some with (item) %} foo {% when None -%} bar {% endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{%- when Some with (item) %} foo {% when None -%} bar {%- endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{%- when Some with (item) %} foo {%- when None %} bar {% endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{%- when Some with (item) %} foo {%- when None %} bar {%- endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{%- when Some with (item) %} foo {%- when None -%} bar {% endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{%- when Some with (item) %} foo {%- when None -%} bar {%- endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{%- when Some with (item) -%} foo {% when None %} bar {% endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{%- when Some with (item) -%} foo {% when None %} bar {%- endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{%- when Some with (item) -%} foo {% when None -%} bar {% endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{%- when Some with (item) -%} foo {% when None -%} bar {%- endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{%- when Some with (item) -%} foo {%- when None %} bar {% endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{%- when Some with (item) -%} foo {%- when None %} bar {%- endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{%- when Some with (item) -%} foo {%- when None -%} bar {% endmatch %} after", "before foo after", "before bar after"); + test_match!("before {% match item %}{%- when Some with (item) -%} foo {%- when None -%} bar {%- endmatch %} after", "before foo after", "before bar after"); +}
Unwanted whitespace in match arm For a Template struct containing a field `ver: Option<&'a str>` and the following template: ```jinja2 {% let suffix -%} {% match ver -%} {% when Some with (ver) -%} {% let suffix = format!("-{}", ver) -%} {% when None -%} {% let suffix = String::new() -%} {% endmatch -%} ``` This code is part of the first match arm: `writer.write_str("\n ")?;`. However, since every line ends with `-%}`, there should't be any newlines inserted into this part of the template. Unwanted whitespace in match arm For a Template struct containing a field `ver: Option<&'a str>` and the following template: ```jinja2 {% let suffix -%} {% match ver -%} {% when Some with (ver) -%} {% let suffix = format!("-{}", ver) -%} {% when None -%} {% let suffix = String::new() -%} {% endmatch -%} ``` This code is part of the first match arm: `writer.write_str("\n ")?;`. However, since every line ends with `-%}`, there should't be any newlines inserted into this part of the template.
I'm wondering where the whitespace between the `match` and the first `when` should go. Whether it should go into the first match arm or before the match expression (thus "into" all match arms). The whitespace before `endmatch` is self-explanatory. In short: ```jinja {% match ... %}[this whitespace]{% when ... %} ``` Should it result in: ```rust match ... { Some(_) => { writer.write_str("[this whitespace]")?; ``` or ```rust writer.write_str("[this whitespace]")?; match ... { ``` @djc? Maybe we should just skip it always? I don't think there's really a natural place for it to go. I'm wondering where the whitespace between the `match` and the first `when` should go. Whether it should go into the first match arm or before the match expression (thus "into" all match arms). The whitespace before `endmatch` is self-explanatory. In short: ```jinja {% match ... %}[this whitespace]{% when ... %} ``` Should it result in: ```rust match ... { Some(_) => { writer.write_str("[this whitespace]")?; ``` or ```rust writer.write_str("[this whitespace]")?; match ... { ``` @djc? Maybe we should just skip it always? I don't think there's really a natural place for it to go.
2020-12-12T16:51:50Z
0.10
2020-12-13T22:08:20Z
49252d2457f280026c020d0df46733578eb959a5
[ "test_match_custom_enum", "test_match_literal_char", "test_match_literal", "test_match_literal_num", "test_match_option", "test_match_ref_deref", "test_extra_whitespace", "test_match_ws" ]
[ "test_match_no_whitespace", "test_cond_ws" ]
[]
[]
auto_2025-06-03
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
4