Search code examples
gogo-templates

How to check if the template node has hyphen when parsing go template?


{{- if .Tools }}
{{- end }}

{{ if .Tools }}
{{ end }}
import (
    "text/template"
    "text/template/parse"
)

t, err := template.New("dummy").Parse(string(templateText))

for _, tt := range t.Templates() {
    for _, n := range tt.Root.Nodes {
        switch n := n.(type) {
        case *parse.IfNode:
            fmt.Println(n.String())
        }
    }
}

This prints the same for both if conditions

{{if .Tools}}
{{end}}

Is it possible to figure out the first if and its end had a hyphen/dash?


Solution

  • Trimming happens during lexical analysis, parser never even sees it. Based on the documentation:

    Trimming spaces. If the action begins "{{- " rather than "{{", then all space/tab/newlines preceding the action are trimmed; conversely if it ends " -}}" the leading spaces are trimmed. This is done entirely in the lexer; the parser never sees it happen.

    So the answer is no, you cannot detect if the input is a trim by looking at the parse tree.

    You can look at the Node.Pos, see the original location in the input text and try to parse it yourself.