/til/

2024 0825 Inline shortcodes

I saw recently that Hugo supports inline shortcodes, allowing you to put the logic for a shortcode in a content file rather than in layouts/shortcodes/....

Depending on how your site’s content is authored, this may have security implications:

It is disabled by default for security reasons. The security model used by Hugo’s template handling assumes that template authors are trusted, but that the content files are not, so the templates are injection-safe from malformed input data. But in most situations you have full control over the content, too, and then enableInlineShortcodes = true would be considered safe. But it’s something to be aware of: It allows ad-hoc Go Text templates to be executed from the content files.
Inline shortcodes

At least for the moment, I’m the only author for any text processed by Hugo on my site. (That might change if I add comments or webmentions to the site content, but it’s how things stand today.)

So I can enable inline shortcodes with the security.enableInlineShortcodes configuration option, and then do something like this. For example, I might want to reference the date of the most recent update to my site in content. There’s a simple builtin function for this called .Site.Lastmod, and you can use Hugo’s time.Format to get the result in the format you prefer, but these are only accessible from templates (layouts), so using them in a content page requires creating a shortcode. With inline shortcodes, I don’t need a separate siteLastmod.html shortcode just to show this date. Instead I can do:

{{< siteLastmod.inline >}}{{ .Site.Lastmod.Format "January 2, 2006" }}{{< /siteLastmod.inline >}}

And that’s how you can read that this site was last modified on October 2, 2024.

The real power is shown by modifying the format. Without inline shortcodes, if I wanted this data on multiple pages, but sometimes as a YYYY-MM-DD datestamp, sometimes as Month D, YYYY, sometimes with a time component, and sometimes with a date compomnent, I would have to build multiple shortcodes or a single shortcode with configuration options. With inline shortcodes, I can format the date the way I want right in the content file.

Responses

Webmentions

Hosted on remote sites, and collected here via Webmention.io (thanks!).

Comments

Comments are hosted on this site and powered by Remark42 (thanks!).