Roundtrip with urls.Parse

How do we parse a url string with urls.Parse, modify the url struct’s fields, and then convert it back into a url string?

Hugo does not provide a function to convert a dictionary of URL components (e.g., scheme, host, port, path, etc.) to a well structured URL string. You will have to build the string manually.

This template code:

{{ $url := "" }}
{{ $urlParsed := urls.Parse $url }}

  Scheme: {{ $urlParsed.Scheme }}
  User: {{ $urlParsed.User }}
  Host: {{ $urlParsed.Host }}
  Hostname: {{ $urlParsed.Hostname }}
  Port: {{ $urlParsed.Port }}
  Path: {{ $urlParsed.Path }}
  EscapedPath: {{ $urlParsed.EscapedPath }}
  Query: {{ $urlParsed.Query }}
  RawQuery: {{ $urlParsed.RawQuery }}
  Fragment: {{ $urlParsed.Fragment }}
  EscapedFragment: {{ $urlParsed.EscapedFragment }}
  RequestURI: {{ $urlParsed.RequestURI }}

Produces this output:

Scheme: https
User: user:password
Port: 8443
Path: /foo bar/baz
EscapedPath: /foo%20bar/baz
Query: map[duey:[Goodbye] huey:[Hello World]]
RawQuery: huey=Hello%20World&duey=Goodbye
Fragment: wibble wobble
EscapedFragment: wibble%20wobble
RequestURI: /foo%20bar/baz?huey=Hello%20World&duey=Goodbye

Hugo’s querify function might be helpful when building query strings.

1 Like

And printf is probably also useful here:

{{ printf "%s%s%s" $urlParsed.Scheme $urlParsed.Host $urlParsed.Path }}