Hugo Shortcodes: Links with target="_blank"

If you do a lot of content development with Hugo then you have probably noticed that by default there is no way to specify the target attribute of a URL. This is especially important when you want a link to launch in a new browser tab.

This solution uses Shortcodes. The Hugo documentation defines a shortcode as “a simple snippet inside a content file that Hugo will render using a predefined template”.

Shortcode links with target='_blank'

Credit: This section is based on the solution originally shared by Leo_merkel in the Hugo discussion forums. I’ve summarised it here to give the concise steps:

  1. In the command prompt navigate to the layouts directory:

    cd C:\Hugo\Sites\mysitename\layouts
  2. Create a new shortcodes folder if it doesn’t already exist:

    mkdir shortcodes
  3. In the shortcodes folder create a new file target-blank.html and add the following:

    <a href="{{ .Get 1 }}" target="_blank">{{ .Get 0 }}</a>
  4. Now we can reference the shortcode in our content:

    {{< target-blank "Title" "https://link-to/" >}}

    Ensuring to replace Title and https://link-to/ as appropriate.

Optional link text

We can take this a step further by giving the option of only specifying a URL, in which case the URL should be rendered as the clickable link text.

  1. Edit the target-blank.html file and replace with the following:

    <a href="{{ .Get "url" }}" target="_blank">{{ with .Get "title" }}{{.}}{{else}}{{.Get "url"}}{{end}}</a>

    There are 2 changes here to note:

    • The parameters are now named rather than positional, so we need to reference the shortcode differently (see next step)
    • We are using with to check if the title parameter is provided, otherwise use the url parameter for the link text.
  2. Reference the shortcode in our content using named parameters:

    {{< target-blank title="Title" url="https://link-to/" >}}