actix / actix/actix-web

Support url_for without requests

Aperta
#1,583 6 commenti 4 reazioni 0 assegnatari Vedi su GitHub
A-web C-feature
Lingua principale
Rust
Stelle
24.8k
Fork
1.9k
Merge medio
23h 10m
PR unite (30g)
26

Descrizione

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).

Guida per i contributori

Apri la guida per i contributori

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.