In this post we’re going to see how to set up your Neovim/Vim editor for editing Hugo HTML Templates.

This website is built with Hugo framework which is written in Golang. As they claimed Hugo is the world’s fastest framework for building websites. And I can’t argue with that since it builds my site — 140 posts - 42,084 words, in just 256 ms.

More importantly I’m very happy working with it. It’s well structured, flexible and has a great documentation.

One thing that bothers me though is coding within it’s template. Hugo uses Go’s html/template package for it’s templating engine. It is a file with extension *.html* but includes go template syntax like {{ .Site.RegularPages }}.

My editor/IDE is Neovim and currently it has no good syntax highlight by default or plugin to deal with this template.

hugo_template_without_highlight

As you can see above the most of syntax highlighting is missing due to the template.

Info

My editor choice is Neovim and I use Vim and Neovim/Nvim words interchangeably.

Solution

In Neovim we have a filetype gohtmltmpl which is just for this go html template. The missing part is finding a go html template pattern in a default html file— if exists, and tell Neovim to set the file to gohtmltmpl instead of htmlfor syntax highlighting.

Thanks to Hugo community I found the related snippet in Hugo Discourse:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function DetectGoHtmlTmpl()
    if expand('%:e') == "html" && search("{{") != 0
        setfiletype gohtmltmpl
    endif
endfunction

augroup filetypedetect
    " gohtmltmpl
    au BufRead,BufNewFile *.html call DetectGoHtmlTmpl()
augroup END

In summary this vimscript snippet checks whether file extension is html and contains term {{ which is associated with gohtmltmpl.

For detail, this below first part searches term {{ and if it founds, it sets the filetype to gohtmltmpl.

1
2
3
4
5
function DetectGoHtmlTmpl()
    if expand('%:e') == "html" && search("{{") != 0
        setfiletype gohtmltmpl
    endif
endfunction

The last part is responsible that every time entering existing or new file — BufRead&BufNewFile, runs the DetectGoHtmlTmpl function.

1
2
3
4
augroup filetypedetect
    " gohtmltmpl
    au BufRead,BufNewFile *.html call DetectGoHtmlTmpl()
augroup END

Put the whole snippet into your configuration file:

# Nvim
~/.config/nvim/init.vim
# Vim
~/.vimrc

And voilà! Now I can see what I code.

hugo_template_with_highlight

You can also put the snippet into one of the more appropriate related configuration file like;

- ~/.config/nvim/filetype.vim
- ~/.config/nvim/ftplugin/gohtmltmpl.vim
- ~/.config/nvim/indent/gohtmltmpl.vim
- ~/.config/nvim/syntax/gohtmltmpl.vim

For more info about this subject you can look at Neovim documentation in runtimepath, :h 'runtimepath'.

All done!