Update book for methods calls

This commit is contained in:
Guillaume Gomez 2024-07-01 17:30:44 +02:00
parent 6c46e4f7b8
commit d0bcba7d1c

View File

@ -245,13 +245,11 @@ struct MyTemplate;
### Struct / trait implementations
Finally, we can invoke functions that are implementation methods of our
template struct, by referencing `Self` (note the uppercase `S`) as the path,
before calling our function:
Finally, we can call methods of our template struct:
```rust
#[derive(Template)]
#[template(source = "{{ Self::foo(self, 123) }}", ext = "txt")]
#[template(source = "{{ foo(123) }}", ext = "txt")]
struct MyTemplate {
count: u32,
};
@ -263,9 +261,8 @@ impl MyTemplate {
}
```
If the implemented method requires a reference to the struct itself,
such as is demonstrated in the above example, we can pass `self`
(note the lowercase `s`) as the first argument.
You can also use `self.foo(123)`, or even `Self::foo(self, 123)`, as you see
fit.
Similarly, using the `Self` path, we can also call any method belonging
to a trait that has been implemented for our template struct:
@ -286,6 +283,32 @@ impl Hello for MyTemplate {
}
```
If you want to call a closure which is a field, you'll need to follow Rust's
syntax by surrounding the call with parens:
```rust
#[derive(Template)]
#[template(source = "{{ (closure)(12) }}", ext = "txt")]
struct MyTemplate {
closure: fn(i32) -> i32,
}
```
## Calling functions
If you only provide a function name, `rinja` will assume it's a method. If
you want to call a method, you will need to use a path instead:
```jinja
{# This is the equivalent of `self.method()`. #}
{{ method() }}
{# This is the equivalent of `self::function()`, which will call the
`function` function from the current module. #}
{{ self::function() }}
{# This is the equivalent of `super::b::f()`. #}
{{ super::b::f() }}
```
## Template inheritance
Template inheritance allows you to build a base template with common