Jetbrains Goland HTML Templates Formatting and Code Completion
Asked Answered
P

2

2

I am using Go HTML Templates in Jetbrains Goland. How do I get all 3: HTML formatting, template code completion, and template formatting for templates?

Assuming I installed Go Templates plugin and I am using "*.tpl" as a file extension for my templates, I have two options:

  1. Settings - Editor - Filetypes - HTML - Add "*.tpl" as an HTML type. PROS: I have an HTML code completion and syntax highlighting with a caveat (see CON 2) CON 1: I do not have code completion on template items, the editor is unaware of templates at all CON 2: Template code blocks are treated as text, i.e. I do not have code indentation for RANGE blocks for example when I try to format my code.

  2. Settings - Editor - Filetypes - Go Templates - Add "*.tpl" as registered type with "HTML" as an underlying type ("Template data language") PROS: I have code completion for 'dots' and can see properties and methods on them (see https://www.jetbrains.com/help/go/integration-with-go-templates.html) CONS: No HTML highlighting, autocompletion, or formatting...

Performative answered 30/3, 2021 at 20:50 Comment(0)
P
6

After hours of research, I finally found the answer:

Settings - Languages and Frameworks - Template Data Languages - Project Language - Set "HTML"

Also, I suggest using "*.go.html" as a Go Templates extension. This way you can see syntax highlighting even when opening the template in VSCode, online on GitHub, etc.

Performative answered 30/3, 2021 at 20:50 Comment(0)
S
2

if you put:

{{- /*gotype: github.com/USERNAME/PROJECTNAME/internal/models.TemplateData*/ -      }}

at the top of your template file, Goland will facilitate code completion for properties and nested properties of the custom data you've introduced to the template from Golang. It will pop up every time you type the dot operator {{.}}. Note that TemplateData is the custom type you pass to the template in 'func (t *Template) Execute(wr io.Writer, data any) error'

https://www.jetbrains.com/help/go/integration-with-go-templates.html

You can even get code completion for custom functions you pass to the template, as long as you make those functions either properties, or methods, of the TemplateData type. The other way to expose custom functions in the template file is to use MYTEMPLATE.Funcs() and pass them in via the template.FuncMap type, but this doesn't allow for code completion as far as I can tell.

https://www.calhoun.io/intro-to-templates-p3-functions/

Sivie answered 7/12, 2023 at 16:3 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.