github.com/fedir/buffalo@v0.11.1/render/html_test.go (about) 1 package render_test 2 3 import ( 4 "bytes" 5 "os" 6 "path/filepath" 7 "strings" 8 "testing" 9 10 "github.com/gobuffalo/buffalo/render" 11 "github.com/gobuffalo/packr" 12 "github.com/stretchr/testify/require" 13 ) 14 15 func Test_HTML(t *testing.T) { 16 r := require.New(t) 17 18 tmpDir := filepath.Join(os.TempDir(), "html_test") 19 err := os.MkdirAll(tmpDir, 0766) 20 r.NoError(err) 21 defer os.Remove(tmpDir) 22 23 tmpFile, err := os.Create(filepath.Join(tmpDir, "test.html")) 24 r.NoError(err) 25 defer os.Remove(tmpFile.Name()) 26 27 _, err = tmpFile.Write([]byte("<%= name %>")) 28 r.NoError(err) 29 30 t.Run("without a layout", func(st *testing.T) { 31 r := require.New(st) 32 33 j := render.New(render.Options{ 34 TemplatesBox: packr.NewBox(tmpDir), 35 }).HTML 36 37 re := j(filepath.Base(tmpFile.Name())) 38 r.Equal("text/html", re.ContentType()) 39 bb := &bytes.Buffer{} 40 err = re.Render(bb, map[string]interface{}{"name": "Mark"}) 41 r.NoError(err) 42 r.Equal("Mark", strings.TrimSpace(bb.String())) 43 }) 44 45 t.Run("with a layout", func(st *testing.T) { 46 r := require.New(st) 47 48 layout, err := os.Create(filepath.Join(tmpDir, "layout.html")) 49 r.NoError(err) 50 defer os.Remove(layout.Name()) 51 52 _, err = layout.Write([]byte("<body><%= yield %></body>")) 53 r.NoError(err) 54 55 re := render.New(render.Options{ 56 TemplatesBox: packr.NewBox(tmpDir), 57 HTMLLayout: filepath.Base(layout.Name()), 58 }) 59 60 st.Run("using just the HTMLLayout", func(sst *testing.T) { 61 r := require.New(sst) 62 h := re.HTML(filepath.Base(tmpFile.Name())) 63 64 r.Equal("text/html", h.ContentType()) 65 bb := &bytes.Buffer{} 66 err = h.Render(bb, map[string]interface{}{"name": "Mark"}) 67 r.NoError(err) 68 r.Equal("<body>Mark</body>", strings.TrimSpace(bb.String())) 69 }) 70 71 st.Run("overriding the HTMLLayout", func(sst *testing.T) { 72 r := require.New(sst) 73 nlayout, err := os.Create(filepath.Join(tmpDir, "layout2.html")) 74 r.NoError(err) 75 defer os.Remove(nlayout.Name()) 76 77 _, err = nlayout.Write([]byte("<html><%= yield %></html>")) 78 r.NoError(err) 79 h := re.HTML(filepath.Base(tmpFile.Name()), filepath.Base(nlayout.Name())) 80 81 r.Equal("text/html", h.ContentType()) 82 bb := &bytes.Buffer{} 83 err = h.Render(bb, map[string]interface{}{"name": "Mark"}) 84 r.NoError(err) 85 r.Equal("<html>Mark</html>", strings.TrimSpace(bb.String())) 86 }) 87 88 }) 89 }