Mojolicious url_for: absolute path
Asked Answered
W

2

11

I'm currently trying to port one of my smaller catalyst apps to Mojolicious (just for the fun of it).

Say that we are on a page: http://whatever.com/generate. On that page there is a link to for example "generated"

When using catalyst (with TT templates) and you define the link as

uri_for 'generated'

it will generate a link to http://whatever.com/generate/generated But if you define it as

uri_for '/generated'

it will generate a link to http://whatever.com/generated

I tried to do the same with Mojolicious' url_for, but it seems to work differently. It doesn't make a differnece wether I call

url_for 'generated'

or

url_for '/generated'

both calls generate a link to '/generate/generated'

So my question is: how do I make url_for generate a link to an absolute route. i.e. to '/generated'

Waggon answered 10/1, 2011 at 12:13 Comment(0)
S
12

url_for generates urls relative to app root. That was done for portability: you may place your app at any url and your links won't get broken.

If you need an link to absolute path, why do you need url_for than? You can use just a string '/generated'.

From other hand, if you really need Mojo::URL object you can get it with

<%= url_for->path('/generated') %>

url_for when called without params returns current url

Soubriquet answered 10/1, 2011 at 13:26 Comment(1)
Indeed. I guess I'm still in a catalyst mindset, always using uri_for. But you're right, I don't need url_for at all :-)Waggon
J
12

You can easily get an absolute url from url_for. It returns a Mojo::URL object, so you can just use the to_abs method:

$ perl -Mojo -E 'a("/" => sub { $s=shift;$s->render(text=>$s->url_for("/")->to_abs) })->start' get /
http://localhost:13733/
Juryrigged answered 1/5, 2012 at 17:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.