About htmlEscape: transform https into https%3A%2F%2F

My question may be naive, but I am looking to turn https://example.com into https%3A%2F%2Fexample.com, and specifically with this type of variable: {{ .Permalink }}. htmlEscape seems to be the solution, but I get no difference between {{ .Permalink | htmlEscape }} and {{ .Permalink }}. Am I missing something?

HTML-escape escapes characters not allowed inside of HTML. What you want is URL-escaping, which escapes all characters that have a meaning in URLs. Urlize should do the trick:

1 Like

If you need to include a URL in a query string:

{{ $base := "https://foo.com" }}
{{ $queryString := querify "url" "https://example.com" }}
{{ printf "%s?%s" $base $queryString }}

Produces:

https://foo.com?url=https%3A%2F%2Fexample.com
1 Like

Many thanks @davidsneighbour and @jmooring! But I just need to convert https://example.com into https%3A%2F%2Fexample.com:

  • urlize does not work (I have the same result with or without urlize :thinking: …)
  • querify it’s interesting but I just need to convert the URL, is there a simpliest way?

No functions that I am aware of. Options:

{{ $url := "https://example.com" }}
{{ $urlEncoded := index (split (querify "" $url) "=" ) 1 }}

{{/* or */}}

{{ $url := "https://example.com" }}
{{ $urlEncoded := replace $url ":" "%3A" -}}
{{ $urlEncoded = replace $urlEncoded "/" "%2F" -}}

@schnerring identified an undocumented function:

{{ urlquery "https://example.com" }} --> https%3A%2F%2Fexample.com

The function takes one or more args, producing a single string.

{{ urlquery "https:/" "/example.com" }} --> https%3A%2F%2Fexample.com

Interesting function, thank you for following up on my questions!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.