Pretty printing GO Template sources

Over time some of my Hugo HTML has gotten a little bit messy… indent/outdent doesn’t match the logic, and I have severe OCD about source code.

I could manually fix all of it, but I was hoping I might find a “pretty printer” that can take the combination of HTML and GO template code and format it nicely. Handling embedded CSS would be a plus, but not a requirement.

I tried to get gofmt running to try that, but the build kept failing with errors and I have no idea why.

Anything out there which would “just work”.

As far as which editor to support: it can be command-line only, but I do use vim and TextMate if solutions there exist.

Thanks!

I use Brackets (from Adobe, very capable and free editor) which uses JS Beautify as formatter.

It works OK, but I usually have to do some adjustments to get my template blocks inline.

See:

Note that the situation improved a lot with the block keyword, which made it easier to create well formed templates without the partial spaghetti.

If you find something that works better, please shout.

I have the same issue in Atom, using Atom Beautify, which also uses JS Beautify behind the scenes.

However, you can override the HTML beautification to use prettydiff which handles the hugo template stuff just fine.

Although I did find one weird thing…given this code:

<img src="{{ printf ("/events/%s/logo-square.png") ($.Scratch.Get "subdir")}}" class="img-responsive"/>

prettydiff will turn it into this:

<img src="{{ printf (" /events/%s/logo-square.png") ($.Scratch.Get " subdir")}}" class="img-responsive"/>

Which is bad news bears, because now the path has a space in it :slight_smile:

1 Like

I also use sublime’s plugin called prettify which also ads space in tag names so than I have to see if it added any space, It would be greater if developer allow spaces for tags like “image” to " image ", as these editors tools add spaces.

For anyone else stumbling to this thread, and if that person is using emacs, the web-mode package works pretty well with GO templates… indentation, commenting, etc.

As you’re web developing chances are good you have already heard of prettier.

It does really good formatting plain js/ts/html/css.

I added a small plugin for it to work with GoHugo: prettier-plugin-go-template.

Setup should be really straight forward – just pay attention to the GoHugo section inside the second URL.