Support url_for without requests
- Lenguaje dominante
- Rust
- Estrellas
- 24.8k
- Forks
- 1.9k
- Merge medio
- 23 h 10 min
- PR fusionados (30 d)
- 26
Descripción
Currently, `url_for[_static]` is defined on `HttpRequest`. This works fine most of the time, but I recently found a case when using Tera that makes this unusable.
In a Tera template, we can call custom functions which are under the hood implemented as Rust functions. For example, this Tera function `url_for(name="foo")` could be implemented in Rust as:
```rust
fn tera_url_for(args: &HashMap) -> Result {
// Here there will be an entry ("name", "foo") in `args`
...
}
```
Now the problem is that `tera_url_for` needs to be registered as a global function, so it doesn't have access to the current request.
I'm thinking it'd be very helpful to expose an API that looks something like this:
```rust
// New type with `url_for` and `url_for_static` methods,
// could be a light wrapper around `ResourceMap`
use actix_web::Routes;
static MY_ROUTES: OnceCell = OnceCell::new();
fn tera_url_for(args: &HashMap) -> Result {
let name = /* get name from args */;
let url = MY_ROUTES.url_for(name);
...
}
fn main() -> io::Result<()> {
HttpServer::new(...)
.inspect_routes(|routes: Routes| { // New method on `App` or `HttpServer`
MY_ROUTES.set(routes).unwrap();
})
.bind(...)?
.run()
.await
}
```
This will also enable us to do cool things like print out the full route table for inspection/documentation purpose at build time, similar to [what Phoenix supports](https://hexdocs.pm/phoenix/routing.html#examining-routes).
Guía de contribución
Evaluación
Este issue todavía no se ha evaluado.