Skip to content

Instantly share code, notes, and snippets.

@AlphaWong
Last active July 17, 2018 14:14
Show Gist options
  • Save AlphaWong/0bf930021a29e9c1309c79202bfcb4a5 to your computer and use it in GitHub Desktop.
Save AlphaWong/0bf930021a29e9c1309c79202bfcb4a5 to your computer and use it in GitHub Desktop.
"text/template" issue for embed string struct
package main
import (
"log"
"os"
"strings"
"text/template"
)
type myStr string
type myStruct struct {
string
}
func main() {
const (
master = `Names:{{block "list" .}}{{"\n"}}{{range .}}{{printf "- %t\n" . }}{{end}}{{end}}`
overlay = `{{define "list"}} {{join . ", "}}{{end}} `
)
var (
funcs = template.FuncMap{"join": strings.Join}
guardians = []interface{}{myStruct{"123"}, "Gamora", "Groot", "Nebula", "Rocket", "Star-Lord"}
)
masterTmpl, err := template.New("master").Funcs(funcs).Parse(master)
if err != nil {
log.Fatal(err)
}
overlayTmpl, err := template.Must(masterTmpl.Clone()).Parse(overlay)
if err != nil {
log.Fatal(err)
}
if err := masterTmpl.Execute(os.Stdout, guardians); err != nil {
log.Fatal(err)
}
if err := overlayTmpl.Execute(os.Stdout, guardians); err != nil {
log.Fatal(err)
}
}
@AlphaWong
Copy link
Author

@AlphaWong
Copy link
Author

AlphaWong commented Jul 17, 2018

A can fmt.Sprintf("%s", A) as a string do not mean A is the type of string which A might be

type MyStruct struct{
    string
}

A := MyStruct{"text"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment