Skip to content

proposal: text/template: add missingkey=ignore #23488

@sean-

Description

@sean-

I'd like to propose extending text/template to include a missingkey=ignore Option(). Sometimes it is desirable to re-parse the template to find the original value and handle or defer processing until all template variables have been provided. In order to do this, text/template needs to pass through the original, invalid or missing value. Here is what I was thinking:

        data := map[string]int{
                "x": 99,
        }
        tmpl, err := New("t1").Parse("{{.x}} {{.y}}")
        if err != nil {
                t.Fatal(err)
        }
        var b bytes.Buffer
        tmpl.Option("missingkey=ignore")
        b.Reset()
        err = tmpl.Execute(&b, data)
        if err != nil {
                t.Fatal("default:", err)
        }
        want = "99 {{ .y }}"
        got = b.String()
        if got != want {
                t.Errorf("got %q; expected %q", got, want)
        }

Note that in want the extra whitespace between the left and right delimiters that was injected. I'm unsure as to whether or not that is actually more correct vs not adding any additional whitespace.

Because text/template's lexer eats whitespace, this isn't perfect, but it does eventually reduce to the correct value. Specifically:

foo {{- .bar}} comes back as foobaz if the variable bar was assigned the value baz. If, however, bar was not part of the variable map, the result would be foo{{ .bar }}.

This limitation seemed acceptable to me. Thoughts?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions