0

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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Jimmy T.
  • 4,033
  • 2
  • 22
  • 38
  • 3
    The code in the question does not produce the error cited: https://play.golang.org/p/xWbjObZCF9h. Please share the actual code that you have problems with. – mkopriva Jan 24 '21 at 10:44
  • @mkopriva oh, true, my mistake. The code I've posted is a trivialized version but it's the one I've actually executed, that is except that I've kept the original code after it in main and wanted to insert a `return` before it to quickly analyze what the problem is. Didn't notice that this code actually worked and the original code that came after caused the cause because the template was the same – Jimmy T. Jan 24 '21 at 13:22
  • If you're still having issues resolving the problem feel free to update the question with a code sample that reproduces the error. – mkopriva Jan 24 '21 at 13:32
  • I did a quick search and that error can be shown if you try to access something that is `nil`. – TehSphinX Jan 24 '21 at 14:11
  • 1
    @TehSphinX something similiar to that actually turned out to be the issue, although in my case it wasn't `nil` but an empty string – Jimmy T. Jan 24 '21 at 21:10

1 Answers1

1

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

TehSphinX
  • 6,536
  • 1
  • 24
  • 34