Add backwards compatibility for new try mechanism introduced in Hugo v0.141.0

Hugo v0.141.0 introduced a new try mechanism to improve error handling. This is a breaking change with older Hugo versions. If your site or theme uses this new try mechanism, the minimum required version of Hugo is therefore v0.141.0.

It may not always be feasible to upgrade to Hugo v0.141.0 or later. Unfortunately, there is no easy way to add backwards compatibility. Go’s template parser fails if you try to use a keyword/function that’s not available in the current running version (see this discussion).

As the author of the Hinode theme, I implemented a different approach that may helpful to others. I isolated all partials and render hooks that reference the new try mechanism. I then created a separate module that includes these files, but uses the “old way” (without try and .Value). Theme users can optionally import this module to make the theme compatible with Hugo <v0.141.0. The import mechanism (it should be imported first in the import order) ensures that the Hugo renderer uses the “old” files instead of the “new” files in the main theme.

Please refer to the module mod-compatibility for an example. Please note that Hugo gives a warning about minimum version requirements, but they can be safely ignored.

4 Likes

Not only that. If you use the “old” .Err way, your theme or module is incompatible with Hugo v0.141.0 and upwards and fails with an ERROR. I expect issues with that to become this Discourse’s new mFAQ (most frequently asked question).

Moving everything into a compatibility module sounds like a great idea. It might be a good idea to add an explicit note that the compatibility module MUST be configured AFTER the original module, so those layout files in there will override the module files with newer methods.