Skip to content

Instantly share code, notes, and snippets.

@ngsctt
Last active September 19, 2022 10:38
Show Gist options
  • Save ngsctt/880da5a555ada9a1b53e20bf7065530c to your computer and use it in GitHub Desktop.
Save ngsctt/880da5a555ada9a1b53e20bf7065530c to your computer and use it in GitHub Desktop.
Shortcode to inject character-escaped emails in Hugo
{{ $mailto := "mailto:" -}}
{{ $email := index .Site.Data.emails (.Get 0 | default "contact") | default .Site.Data.emails.contact }}
<a {{ print "href=" $mailto $email | safeHTMLAttr }}>{{ safeHTML $email }}</a>
contact: '&#117;&#115;&#101;&#114;&#064;&#101;&#120;&#097;&#109;&#112;&#108;&#101;&#046;&#099;&#111;&#109;'

Without plugins, it's difficult to use obfuscated email addresses in Hugo. Additionally, Hugo will aggressively escape anything you introduce to a template, especially if it's a href attribute.

To use a character entities obfuscation technique (eg. that of http://wbwip.com/wbw/emailencoder.html), place email.html in the layouts/shortcodes folder, and place emails.yml in the data folder.

The contact email in emails.yml is the character entity-encoded form of user@example.com. It will be the default email used if you call the email shortcode (by using {{< email >}} or {{< email contact >}} in your page content) without any parameters. You can add other emails to emails.yml and use them in the email shortcode by passing their key as a parameter, eg: {{< email newKey >}}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment