URLencode in Hugo

Hi! I’d like to create share buttons without tracking scripts and cookies in my template, but to do that, I need to urlencode my Permalink.

What I mean by “urlencode” is the transformation this online tool operates.

For instance, I could create a Facebook button by adding a link to http://www.facebook.com/sharer/sharer.php?u={{ .Permalink | urlencodeThisSomehow }}

I tried looking at what Go offers for URLs. PathEscape seems to be the equivalent, but it does not seem to be available in Hugo templates.

I suppose I could create a partial to do this by combining regex, urls.Parse and Go’s URL.EscapedPath, but this looks quite complicated indeed for this operation.

Do you know of a proper way to do this?

You might be able to use https://gohugo.io/functions/htmlescape/.

Sadly no. HtmlEscape is used to display special characters can be displayed in an HTML page, while URLencode/PathEscape escapes special characters so that they can be used in a URL. The encoding rules are not the same.

In my share partial:
<a href=“https://www.facebook.com/sharer/sharer.php?u={{ .Permalink }}”
<a href=“https://twitter.com/intent/tweet?url={{ .Permalink }}&text={{ .Title }}&hashtags={{ .Params.hash }}&via={{ .Site.Params.twitter.username }}”

If you look at source code of page on web, this renders as: (changed less than bracket to dots - would not show)
… a title=“Share on Facebook” class=“link dib h2 w2 mr3” href=“https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fwww.Domain.com%2Fsubdir%2Fpage.htm” target="_blank" rel=“noopener” …

as you can see, this is urlencoded. And it works, share to fb, twitter and email.

Note on AMP version of site, use amp-social-share
…amp-social-share class=“mr3 dim” type=“facebook” data-param-app_id=“259967834022664” width=“42” height=“42” data-param-href="{{ .Permalink }}"></amp-social-share…

1 Like

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