A way to add parameters to image and link render hooks

While there’s a proposal to add parameters to render hooks, I found a somewhat decent solution which uses the title attribute and the transform.Unmarshal function.

Links and images in markdown allow you to specify a title parameter.

![Alt text 'title'](url)
[Link text](url 'title')

Using the transform.Unmarshal function, we can set the title to a JSON string which can then make the parameters.

For example, here’s how you can use the title to add additional attributes to the rendered link tag.

In layouts/_default/_markup/render-link.html, add the following.

{{ $scratch := newScratch }}
{{ if ne .Title "" }}
    {{ with .Title }}
        {{ $options := transform.Unmarshal . }}
        {{ $scratch.Set "attrs" slice }}
        {{ range $key, $val := $options }}
            {{ $scratch.Add "attrs" (printf `%s="%s"` $key $val)}}
        {{ end }}
    {{ end }}
{{ end }}
<a href="{{ .Destination }}" {{ with (delimit ($scratch.Get "attrs") " ")  -}}{{ . | safeHTMLAttr }}{{- end }}>{{ .Text | safeHTML }}</a>

With that, if I use this for example

[Farai's Personal Website]( '{"rel":"nofollow"}')

It will result in this html

<a href="" rel="nofollow">Farai's Personal Website</a>

A few issues with this approach however

  • The title must be surrounded with single quotes since JSON only allows double quotes to specify keys and values.
  • If you want to use a single quote as a key or value, you need to use &#39; (the escaped quote). That’s because the single quotes is used to open and close the title block. Trying to escape it with a backslash will result in an error.
  • Technically you can use TOML and YAML for the title since transform.Unmarshal supports them but I haven’t tried it.