Hugo

How to add a theme using modules (for beginners)

It took me longer than I expected to figure out how to add a theme to a site the new way: using modules. It is very easy — much easier than the two other methods I’d used to add themes — once you know what you need to do. Here’s how it worked, in three short steps.

First, at the command line, go to the top level of your project. Initialize your site as a hugo module. To do that, type hugo mod init and then the url where the site will be deployed (without a trailing slash at the end). For example:

hugo mod init yourname.github.io/sitename

for GitHub Pages user yourname deploying sitename.

Second, add the theme as a module in your config file. Here is how it looks to load the hugo-xmin theme in a config file which uses the default toml format:

[module]

  [[module.imports]]
    path = "github.com/yihui/hugo-xmin"
    disable=false

The [module] indicates that this is a section of the config file for modules, and then the path is just the url fetched from GitHub for the theme I wanted to add. A second theme could even be added below, in the same format, especially if one of them is marked disable=true. That even allows quick switching between themes!

Third, tell hugo to use this theme. That looks like adding the following to your config.toml file, where hugo-xmin is the name of the theme:

theme = ["hugo-xmin"]

Note that this command will also look at a series of theme items or other code, prioritizing the ones on the left, so the following would load the hugo-xmin theme, adding to it (and overriding it) with anything in the my-shortcodes module:

theme = ["my-shortcodes", "hugo-xmin"]

To use that module of course we would have had to load it, with something like

  [[module.imports]]
    path = "github.com/yourname/my-shortcodes"
    disable=false

And you now have a theme loaded with your extras.

(Corrections and improvements from more advanced users welcome!)

6 Likes

Great. One little correction:

This:

[module]
  [[module.imports]]
    path = "github.com/yihui/hugo-xmin"
  [[module.imports]]
    path = "github.com/yourname/my-shortcodes"

Is the same as:

theme = ["github.com/yihui/hugo-xmin",  "github.com/yourname/my-shortcodes" ]

You don’t need both.

4 Likes