Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

Re^3: Mojolicious absolute url with query in template? (updated)

by haukex (Archbishop)
on Mar 19, 2020 at 09:35 UTC ( #11114463=note: print w/replies, xml ) Need Help??

in reply to Re^2: Mojolicious absolute url with query in template?
in thread Mojolicious absolute url with query in template?

Oh, I think I see what you're getting at. Note the documentation for url_with:

Does the same as "url_for", but inherits query parameters from the current request.

<update> Expanded url_for vs. url_with examples. </update>

#!/usr/bin/env perl use Mojolicious::Lite -signatures; get '/' => sub ($c) { if ( !$c->param('foo') ) { $c->redirect_to( $c->url_for('index')->query(foo=>"bar") ) } else { $c->render('index') } } => 'index'; app->start; __DATA__ @@ index.html.ep % layout 'main', title => 'Hello, World!'; <pre> %= url_for('/') %= url_for('/')->to_abs %= url_for('/')->to_abs->query(abc=>"xyz") %= url_with('/') %= url_with('/')->to_abs %= url_with('/')->to_abs->query(abc=>"xyz") </pre> @@ layouts/main.html.ep <!DOCTYPE html> <html> <head><title><%= title %></title></head> <body><main> <%= content %> </main></body> </html>

Visiting http://localhost:3000/ results in a single redirect (to add the query for demonstration purposes), and then renders as:

/ http://localhost:3000/ http://localhost:3000/?abc=xyz /?foo=bar http://localhost:3000/?foo=bar http://localhost:3000/?abc=xyz

Also, note the link_to helper: %= link_to Reload => url_with('/')->to_abs results in <a href="http://localhost:3000/?foo=bar">Reload</a>

Replies are listed 'Best First'.
Re^4: Mojolicious absolute url with query in template?
by Anonymous Monk on Mar 19, 2020 at 09:54 UTC
    Thank you haukex! I tried url_with too but was doing something stupid that only returned the query string:
    Your answer (of course) returns the absolute request url with query string:
    Also those link_to helpers are super cool. Now I see what Corion meant by passing params to the query method and why I'd want to do that.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11114463]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2022-10-02 16:58 GMT
Find Nodes?
    Voting Booth?
    My preferred way to holiday/vacation is:

    Results (11 votes). Check out past polls.