M
M
ML2017-03-02 21:42:16
go
ML, 2017-03-02 21:42:16

No such template "content"?

There is a template with the string:
{{ template "content" . }}
The problem is that this template does not always exist.
Is there something like:

{{ if template "content" . }}
{{ template "content" . }}
{{end}}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2017-03-03
@staffID

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 question

Ask a Question

731 491 924 answers to any question