Is there a built in function in Hugo for encoding URLs? And if yes, how to use it in a partial? Thanks
The above question is for social share buttons
If I understand your question, it’s automatic in Go templates. Just output a string inside an href or img src value.
Hi @moorereason
I have a related question. I am told that parameters to the facebook sharer are to be encoded, since the post url itself is a parameter to the facebook sharer url. I noticed the following snippet in the facebook sharer div of the single page template.
<a href="http://www.facebook.com/sharer.php?src=bm&u={{ .Permalink }}&t={{ .Title }}" onclick="window.open(this.href, 'PCwindow', 'width=550, height=350, menubar=no, toolbar=no, scrollbars=yes'); return false;"><i class="fa fa-facebook"></i></a>
Are you saying that Hugo (built on Go) will automatically encode the values retrieved for {{ .Permalink }}
and {{ .Title }}
, so I don’t have to do anything extra to encode these 2 parameters?
Thank you!
Yes, that is what he says. Does your tests prove different?
@bep but how can we do if I’m using printf
or other string templating function?
I mean my current theme allow user to add any sharing providers (not just facebook, g+ and common occidental others), therefore on config.toml
I would like to get something like
[[params.sharingOptions]]
name = "facebook"
icon = "fa-facebook-official"
url = "https://www.facebook.com/sharer/sharer.php?u=%s"
Where I will use printf
to replace %s
like following href="{{ (printf .url $.Permalink) }}"
but in that case Permalink
url will not encoded
Update: the current by-pass I found is that way
{{ printf .url (substr (querify "x" $.Permalink) 2) }}
fwiw, I ended up doing it like this:
{{ $encodedURL := strings.TrimPrefix "=" (querify "" .url) }}
(Hugo v0.47.1)
Just wanted to point out, substitute “querify” with “htmlEscape” for the correct result.
I’ve been having the same issue. I’ve poked around in the Hugo code base and found the solution. There’s an undocumented built-in Hugo function wrapping the Golang url.QueryEscape
function:
You can use it like the following:
{{ urlquery .Permalink }}