Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
You can write your own function for this: https://play.golang.org/p/l6MIC1ZHZA
package main
import (
"bytes"
"fmt"
"html/template"
"log"
)
type Data struct {
Name string
}
func main() {
var tmpl *template.Template
funcMap := template.FuncMap{
"executeIfExists": func(name string, data interface{}) template.HTML {
t := tmpl.Lookup(name)
if t == nil {
return ""
} else {
buf := bytes.NewBuffer([]byte{})
err := t.Execute(buf, data)
if err != nil {
log.Printf("Error executing template '%s': %v", name, err)
return ""
} else {
return template.HTML(buf.Bytes())
}
}
},
}
tmpl = template.Must(template.New("main").Funcs(funcMap).
Parse(`Content: {{ executeIfExists "content" . }} {{ executeIfExists "someAbsentTemplate" . }}`))
tmpl = template.Must(tmpl.New("content").Parse(`Hello, <b>{{ .Name }}</b>!`))
data := Data{
Name: "John",
}
buf := bytes.NewBuffer([]byte{})
err := tmpl.ExecuteTemplate(buf, "main", data)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(buf.Bytes()))
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question