DEV Community


Posted on

Hugo: use partials in shortcodes

Recently, I had this edge case with various shortcodes having quite the same HTML markup in common.

Hugo lets you use shortcodes in markdown files (used for content) as shortcuts to load custom templates. You might use HTML directly instead, but that would be way less maintainable.

One of my favorite features is the ability to organize shortcodes in subfolders inside the layouts/shortcodes directory. You can even nest shortcodes inside other shortcodes!

Source: Hugo documentation - Create Your Own Shortcodes

However, you may want to use some kinda of includes to prevent unnecessary duplication across several templates:

<!-- layouts/shortcodes/myshortcode.html -->
<!-- layouts/shortcodes/myshortcode2.html -->
{{ $param1 := .Get 0 }}
{{ partial "mypartial" (dict "param1" $param1) }}
Enter fullscreen mode Exit fullscreen mode
  • You can grab $param1 in both layouts/shortcodes/myshortcode.html and layouts/shortcodes/myshortcode2.html
  • The partial's location would be layouts/partials/mypartial.html
  • You may use named parameters instead of positional parameters, so .Get 0 becomes .Get "myparameter", which I find more readable that .Get 0, .Get 1, .Get 2, etc.

Then, in the template files:

<div class="myhtml">
{{ with .param1 }}
    {{ . }}
{{ end }}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)