Skip to content

Custom link shortcode

In most cases Hugo’s Render Hooks(Opens in new window) are suitable but if needing to support other features, such as adding a language attribute, the following shortcode might be useful.

Examples

{{< link text="Yle (Suomi)" url="https://yle.fi/" external=1 lang=1 >}}
{{< link text="Yle (Svenska)" url="https://yle.fi/" external=1 lang="sv" >}}

Shortcode template

Link to shortcode template on GitHub(Opens in new window)

{{ $linkText := .Get "text" }}
{{ $linkUrl := .Get "url" }}
{{ $external := .Get "external" }}
{{ $lang := .Get "lang" }}

<!-- Catch any options for true or defaults -->
{{ $languageCode := "fi" }}
{{ if or (ne $lang 1) (ne $lang true) (ne $lang "true") (ne $lang "fi") }}
  {{ $languageCode = $lang }}
{{ end }}

<a href="{{ $linkUrl }}" {{ if $external }}target="_blank"{{ end }}>
  {{- if $external -}}<span {{ if $languageCode }}lang="{{ $languageCode }}"{{ end }}>{{- end -}}{{ $linkText }}{{- if $external -}}</span><span class="pl-2 pr-0.5">{{ partial "icons/external" . }}</span><span class="sr-only">(Opens in new window)</span>{{- end -}}
</a>

Note: The condensed anchor in the shortcode template is to ideally prevent excess spaces between the text and (possible) external icon.