Is there a relatively easy way to implement @mentions?

Hello everyone!

I’m wondering if I can somehow convert @member_id to something like

{{ with (.Site.GetPage "/team/member_id" }}
	<a href="{{ .RelPermalink }}"> {{ .Params.firstName }} {{ .Params.lastName }} </a>
{{ end }}

I’m aware of shortcodes (in fact it is implemented as a shortcode at the moment), however for this particular case I would prefer to have a more concise syntax.

Markdown

[](@jdoe)

layouts/_default/_markup/render-link.html

{{ if strings.HasPrefix .Destination "@" }}
  {{ with site.GetPage (path.Join "team" (substr .Destination 1)) }}
    {{ $anchor := "" }}
    {{ if and .Params.firstName .Params.lastName }}
      {{ $anchor = printf "<a href=%q>%s %s</a>" .RelPermalink .Params.firstName .Params.lastName }}
    {{ else if .Title }}
      {{ $anchor = printf "<a href=%q>%s</a>" .RelPermalink .Title }}
    {{ else }}
      {{ $anchor = printf "<a href=%q>%s</a>" .RelPermalink $.Destination }}
    {{ end }}
    {{ $anchor | safeHTML }}
  {{ else }}
    {{ errorf "Unable to find the %q team member. See %s" (substr .Destination 1) .Page.File }}
  {{ end }}
{{ else }}
  <a href="{{ .Destination }}" {{- with .Title }} title="{{ . }}" {{- end }}>{{ .Text | safeHTML }}</a>
{{ end }}

See https://gohugo.io/templates/render-hooks/.

If that’s not acceptable, you could search/replace .Content prior to rendering.

8 Likes

Thank you, that is quite elegant! I was already thinking about render hooks but didn’t come to the idea of making a valid markdown link in the source file.

I will ask my colleagues if they like [](@jdoe) syntax, but I personally don’t mind.

Here’s an example site that demonstrates both approaches (render hook and content parsing):

git clone --single-branch -b hugo-forum-topic-39912 https://github.com/jmooring/hugo-testing hugo-forum-topic-39912
cd hugo-forum-topic-39912
hugo server

Files of interest:

  • content/_index.md (markdown)
  • layouts/_default/_markup/render-link.html
  • layouts/_default/home.html
2 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.