bou.ke/statictemplate@v0.0.0-20180821122055-510411a5e7dd/statictemplate/html_translate_test.go (about)

     1  package statictemplate
     2  
     3  import (
     4  	"go/types"
     5  	"gopkg.in/stretchr/testify.v1/assert"
     6  	"html/template"
     7  	"testing"
     8  )
     9  
    10  func TestCompileHTMLTemplate(t *testing.T) {
    11  	for _, c := range []struct {
    12  		input, expected string
    13  	}{
    14  		{`<!doctype html>
    15  <html>
    16  <head>
    17  <title>{{ . }}</title>
    18  </head>
    19  <body ref="{{ . }}">
    20  {{ . }}
    21  </body>
    22  </html>
    23  `, `package main
    24  
    25  import (
    26    "bou.ke/statictemplate/funcs"
    27    "io"
    28  )
    29  
    30  func Name(w io.Writer, dot string) (err error) {
    31    defer func() {
    32      if recovered := recover(); recovered != nil {
    33        var ok bool
    34        if err, ok = recovered.(error); !ok {
    35          panic(recovered)
    36        }
    37      }
    38    }()
    39    return fun0(w, dot)
    40  }
    41  
    42  // template.tmpl(string)
    43  func fun0(w io.Writer, dot string) error {
    44    _, _ = io.WriteString(w, "<!doctype html>\n<html>\n<head>\n<title>")
    45    _, _ = io.WriteString(w, funcs.Rcdataescaper(dot))
    46    _, _ = io.WriteString(w, "</title>\n</head>\n<body ref=\"")
    47    _, _ = io.WriteString(w, funcs.Attrescaper(dot))
    48    _, _ = io.WriteString(w, "\">\n")
    49    _, _ = io.WriteString(w, funcs.Htmlescaper(dot))
    50    _, _ = io.WriteString(w, "\n</body>\n</html>\n")
    51    return nil
    52  }`},
    53  	} {
    54  		temp := template.Must(template.New("template.tmpl").Parse(c.input))
    55  		actual, err := Translate(temp, "main", []TranslateInstruction{
    56  			{"Name", "template.tmpl", types.Typ[types.String]},
    57  		})
    58  		if assert.NoError(t, err, c.input) {
    59  			equalish(t, c.expected, actual, c.input)
    60  		}
    61  	}
    62  }