Formatter for Go templates

I may have said at some point that I worked on a formtatter for Go templates. That turned out to be too much work/too hard.

But in the mean time the Go template plugin for Prettier has matured to a point where it’s very good.

I use it with VS Code. I had some trouble getting it to work. The clue, I eventually figured out, is that the plugin + prettier cannot be installed globally. This, I thought, was unfortunate, as I have many Hugo projects.

But then I remembered that Node/NPM is searching the node_modules folders up the tree until it find what it’s looking for.

So, what I have done in my development root:

cd /Users/bep/dev
npm init
npm -i prettier prettier-plugin-go-template --save-dev

Then you need to tell Prettier to use the plugin. Here’s my .prettierrc config file:

Edit in Nov 2023: See pnpm package manager: Couldn't resolve parser "go-template" · Issue #63 · NiklasPor/prettier-plugin-go-template · GitHub

{
  "overrides": [
    {
      "files": ["*.html"],
      "options": {
        "parser": "go-template",
        "goTemplateBracketSpacing": true,
        "bracketSameLine": true
      }
    },
    {
      "files": ["*.js", "*.ts"],
      "options": {
        "useTabs": true,
        "printWidth": 120,
        "singleQuote": true
      }
    }
  ]
}

With the above in place, you can install the VS Code extension:

11 Likes

I’ve been using the .prettierrc file w/ Tailwind for some time on w/ JetBrains products, but with the occasional template bug. Thank you for pointing out the go-template plugin as this should solve those issues.

2 Likes

I had my formatting setup broken in VSCode today for some magical reason. See this for (my) resolution: pnpm package manager: Couldn't resolve parser "go-template" · Issue #63 · NiklasPor/prettier-plugin-go-template · GitHub

2 Likes