Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

Dynamic fields with Go html template

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

question from:https://stackoverflow.com/questions/65869325/dynamic-fields-with-go-html-template

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...