package tplx import ( htmlT `html/template` `log` "testing" txtT `text/template` ) const ( txtTplNm string = "my_txt_template" htmlTplNm string = "index.html" tgtTxt string = "Greetings, Bob!\n" tgtHtml string = "\n\n\t\n\t\t\n\t\tHello, Bob!\n\t\n\t\n\t\t

Hello, Bob. Good to see you.

\n\t\n\n" tTplStr string = "Greetings, {{ .Name }}!\n" hTplStr string = ` Hello, {{ .Name }}!

Hello, {{ .Name }}. Good to see you.

` ) var ( tTpl *txtT.Template = txtT.Must(txtT.New(txtTplNm).Parse(tTplStr)) hTpl *htmlT.Template = htmlT.Must(htmlT.New(htmlTplNm).Parse(hTplStr)) o struct{ Name string } = struct{ Name string }{ Name: "Bob", } ) func TestTpl(t *testing.T) { var err error var s string // if s, err = TplToStr[*txtT.Template](tTpl, o); err != nil { if s, err = TplToStr(tTpl, o); err != nil { t.Fatalf("Failed to render text template to string: %v\n", err) } t.Logf("Text template (%#v): '%s'", s, s) if s != tgtTxt { t.Fatalf("Mismatch on text template '%s'", s) } // if s, err = TplToStr[*htmlT.Template](hTpl, o); err != nil { if s, err = TplToStr(hTpl, o); err != nil { log.Panicf("Failed to render HTML template to string: %v\n", err) } t.Logf("HTML template (%#v):\n%s", s, s) if s != tgtHtml { t.Fatalf("Mismatch on HTML template '%s'", s) } } func TestTplStr(t *testing.T) { var err error var s string if s, err = TplStrToStr(tTplStr, TplTypeText, o); err != nil { t.Fatalf("Failed to render text template to string: %v\n", err) } t.Logf("Text template (%#v): '%s'", s, s) if s != tgtTxt { t.Fatalf("Mismatch on text template '%s'", s) } if s, err = TplStrToStr(hTplStr, TplTypeHtml, o); err != nil { log.Panicf("Failed to render HTML template to string: %v\n", err) } t.Logf("HTML template (%#v):\n%s", s, s) if s != tgtHtml { t.Fatalf("Mismatch on HTML template '%s'", s) } } func TestTplWith(t *testing.T) { var err error var s string if s, err = TplToStrWith(tTpl, txtTplNm, o); err != nil { t.Fatalf("Failed to render text template to string: %v\n", err) } t.Logf("Text template (%#v): '%s'", s, s) if s != tgtTxt { t.Fatalf("Mismatch on text template '%s'", s) } if s, err = TplToStrWith(hTpl, htmlTplNm, o); err != nil { log.Panicf("Failed to render HTML template to string: %v\n", err) } t.Logf("HTML template (%#v):\n%s", s, s) if s != tgtHtml { t.Fatalf("Mismatch on HTML template '%s'", s) } }