Add deref builtin filter

This commit is contained in:
Guillaume Gomez 2024-04-27 12:37:19 +02:00 committed by René Kijewski
parent b668774f9b
commit ed512051cf
3 changed files with 41 additions and 2 deletions

View File

@ -1230,6 +1230,7 @@ impl<'a> Generator<'a> {
) -> Result<DisplayWrap, CompileError> {
match name {
"as_ref" => return self._visit_as_ref_filter(buf, args),
"deref" => return self._visit_deref_filter(buf, args),
"escape" | "e" => return self._visit_escape_filter(buf, args),
"fmt" => return self._visit_fmt_filter(buf, args),
"format" => return self._visit_format_filter(buf, args),
@ -1263,6 +1264,20 @@ impl<'a> Generator<'a> {
Ok(DisplayWrap::Unwrapped)
}
fn _visit_deref_filter(
&mut self,
buf: &mut Buffer,
args: &[Expr<'_>],
) -> Result<DisplayWrap, CompileError> {
let arg = match args {
[arg] => arg,
_ => return Err("unexpected argument(s) in `deref` filter".into()),
};
buf.write("*");
self.visit_expr(buf, arg)?;
Ok(DisplayWrap::Unwrapped)
}
fn _visit_json_filter(
&mut self,
buf: &mut Buffer,

View File

@ -24,6 +24,7 @@ Enable it with Cargo features (see below for more information).
[`as_ref`][#as_ref],
[`capitalize`][#capitalize],
[`center`][#center],
[`deref`][#deref],
[`escape|e`][#escape],
[`filesizeformat`][#filesizeformat],
[`fmt`][#fmt],
@ -108,6 +109,24 @@ Output:
- a -
```
### deref
[#deref]: #deref
Dereferences the given argument.
```
{% let s = String::from("a")|as_ref %}
{% if s|deref == String::from("b") %}
{% endif %}
```
will become:
```
let s = &String::from("a");
if *s == String::from("b") {}
```
### escape | e
[#escape]: #escape--e

View File

@ -311,7 +311,12 @@ fn test_json_script() {
}
#[derive(askama::Template)]
#[template(source = "{% let word = s|as_ref %}{{ word }}", ext = "html")]
#[template(
source = r#"{% let word = s|as_ref %}{{ word }}
{%- let hello = String::from("hello") %}
{%- if word|deref == hello %}1{% else %}2{% endif %}"#,
ext = "html"
)]
struct LetBorrow {
s: String,
}
@ -321,5 +326,5 @@ fn test_let_borrow() {
let template = LetBorrow {
s: "hello".to_owned(),
};
assert_eq!(template.render().unwrap(), "hello")
assert_eq!(template.render().unwrap(), "hello1")
}