How to indicate safe links from post

Viewed 90
2 Answers

Solution using shortcodes

To solve the issue I created a shortcode named file_link.html:

<a href="file://{{ .Get 1 | safeURL }}">{{ .Get 0 }}</a>

That way i can use on the body of the post:

{{< file_link "this text is shown" "/path/to/file" >}}

Which would be equivalent to:

[this text is shown](file:///path/to/file )

Solution 1 – overwrite the default link rendering

You can tell Goldmark (the renderer) how it should render links (see docs), by creating a file in layouts/_default/_markup/render-link.html. This code should help, just make sure that it renders everything it should render in your case (see the mentioned docs what variables you can use in the file):

<!-- layouts/_default/_markup/render-link.html -->
<a href="{{ .Destination | safeURL }}">{{ .Text }}</a>

Note that the magic here is caused by the safeURL function (documentation). If you want to use the safeURL function only when the URL starts with file://, you can do something like this:

<!-- layouts/_default/_markup/render-link.html -->
{{ if hasPrefix .Destination "file://" }}
    <a href="{{ .Destination | safeURL }}">{{ .Text }}</a>
{{ else }}
    <a href="{{ .Destination }}">{{ .Text }}</a>
{{ end }}

Solution 2 – enable unsafe rendering in config (not recommended)

You can also enable rendering of all potentially unsafe links (and also HTML) everywhere by updating your configuration file (respectively the Goldmark renderer settings) like in the examples below. Search for an unsafe field in this part of Hugo docs.

You shouldn't use this unless it's the only acceptable solution for you. It enables rendering URLs like javascript:unsafeFunction() or HTML tags, which may not be what you want to allow.

TOML syntax (config.toml)

[markup]
    [markup.goldmark]
        [markup.goldmark.renderer]
            unsafe = true

YAML syntax (config.yml)

markup:
  goldmark:
    renderer:
      unsafe: true
Related