actix / actix/actix-web

Support url_for without requests

Offen
#1,583 6 Kommentare 4 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen
A-web C-feature
Vorherrschende Sprache
Rust
Sterne
24.8k
Forks
1.9k
Ø Merge
23 Std. 10 Min.
Gemergte PRs (30 T.)
26

Beschreibung

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

Beitragsleitfaden

Beitragsleitfaden öffnen

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.