Dynamic fields with Go html template

1k Views Asked by At

Can I make a html template in go work with dynamic properties?

Like this for example currently results in the error

Invalid template: template: sticker.CellRepresentation:1:23: executing "sticker.CellRepresentation" at <.sticker_set.url>: can't evaluate field url in type interface {}

func sample() error {
    tpl, err := template.New("sample").Parse(`<a href="${sticker_set.url}">{{.sticker_set.url}}</a>`)
    if err != nil {
        return err
    }

    data := map[string]interface{}{
        "sticker_set": map[string]interface{}{
            "url": "x",
        },
    }

    if err := tpl.Execute(NoopWriter{}, data); err != nil {
        return fmt.Errorf("Invalid template: %w", err)
    }

    return nil
}

func main() {
    err := sample()
    if err != nil {
        panic(err)
    }
}

I'm not using structs because the template I'm trying to execute works with a json of a structure that's not defined at compile time

1

There are 1 best solutions below

0
On

Your example works fine for me and on the playground. I adjusted the template a bit and used os.stdout as writer.

func sample() error {
    tpl, err := template.New("sample").Parse(`<a href="{{.sticker_set.url}}">{{.sticker_set.url}}</a>`)
    if err != nil {
        return err
    }

    data := map[string]interface{}{
        "sticker_set": map[string]interface{}{
            "url": "xyz",
        },
    }

    if err := tpl.Execute(os.Stdout, data); err != nil {
        return fmt.Errorf("Invalid template: %w", err)
    }

    return nil
}

Even tried it with different value types: Playground