Please take a look at
https://go.dev/play/p/dTDR50dtHB0
I want to
- define my template data dynamically from yaml
- and export the yaml data if they are unexported
I.e., for the following code:
t := template.New("")
t, err = t.Parse("It's {{.A}} {{.B.C}}!\n")
if err != nil {
log.Fatalf("error: %v", err)
}
t.Execute(os.Stdout, m)
The input is `map[A:Easy! B:map[C:2 D:[3 4]]]`.
But why the template was not able to produce any output for the dynamic
fields?
The error is `<.A>: can't evaluate field A in type map[main.MyKey]interface
{}`
Why is that and how to fix it please?
Thanks
PS. Whole program included below:
-------------------------------------
package main
import (
"fmt"
"log"
"os"
"strings"
"text/template"
"gopkg.in/yaml.v3"
)
var data = `
a: Easy!
b:
c: 2
d: [3, 4]
`
type MyKey string
func (k *MyKey) UnmarshalYAML(n *yaml.Node) error {
var s string
if err := n.Decode(&s); err != nil {
return err
}
*k = MyKey(strings.ToUpper(s))
return nil
}
func main() {
m := make(map[MyKey]any)
err := yaml.Unmarshal([]byte(data), &m)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- m:\n%v\n\n", m)
d, err := yaml.Marshal(&m)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- m dump:\n%s\n\n", string(d))
t := template.New("")
t, err = t.Parse("It's {{.A}} {{.B.C}}!\n")
if err != nil {
log.Fatalf("error: %v", err)
}
err = t.Execute(os.Stdout, m)
if err != nil {
log.Fatalf("error: %v", err)
}
}
-------------------------------------
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/3f7484d6-fbcd-4b88-aeeb-f581e9eb4952n%40googlegroups.com.