| 1 | # Render [](http://godoc.org/github.com/unrolled/render) [](https://github.com/unrolled/render/actions) |
| 2 | |
| 3 | |
| 4 | Render is a package that provides functionality for easily rendering JSON, XML, text, binary data, and HTML templates. |
| 5 | |
| 6 | ## Usage |
| 7 | Render can be used with pretty much any web framework providing you can access the `http.ResponseWriter` from your handler. The rendering functions simply wraps Go's existing functionality for marshaling and rendering data. |
| 8 | |
| 9 | - HTML: Uses the [html/template](http://golang.org/pkg/html/template/) package to render HTML templates. |
| 10 | - JSON: Uses the [encoding/json](http://golang.org/pkg/encoding/json/) package to marshal data into a JSON-encoded response. |
| 11 | - XML: Uses the [encoding/xml](http://golang.org/pkg/encoding/xml/) package to marshal data into an XML-encoded response. |
| 12 | - Binary data: Passes the incoming data straight through to the `http.ResponseWriter`. |
| 13 | - Text: Passes the incoming string straight through to the `http.ResponseWriter`. |
| 14 | |
| 15 | ~~~ go |
| 16 | // main.go |
| 17 | package main |
| 18 | |
| 19 | import ( |
| 20 | "encoding/xml" |
| 21 | "net/http" |
| 22 | |
| 23 | "github.com/unrolled/render" |
| 24 | ) |
| 25 | |
| 26 | type ExampleXml struct { |
| 27 | XMLName xml.Name `xml:"example"` |
| 28 | One string `xml:"one,attr"` |
| 29 | Two string `xml:"two,attr"` |
| 30 | } |
| 31 | |
| 32 | func main() { |
| 33 | r := render.New() |
| 34 | mux := http.NewServeMux() |
| 35 | |
| 36 | mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { |
| 37 | w.Write([]byte("Welcome, visit sub pages now.")) |
| 38 | }) |
| 39 | |
| 40 | mux.HandleFunc("/data", func(w http.ResponseWriter, req *http.Request) { |
| 41 | r.Data(w, http.StatusOK, []byte("Some binary data here.")) |
| 42 | }) |
| 43 | |
| 44 | mux.HandleFunc("/text", func(w http.ResponseWriter, req *http.Request) { |
| 45 | r.Text(w, http.StatusOK, "Plain text here") |
| 46 | }) |
| 47 | |
| 48 | mux.HandleFunc("/json", func(w http.ResponseWriter, req *http.Request) { |
| 49 | r.JSON(w, http.StatusOK, map[string]string{"hello": "json"}) |
| 50 | }) |
| 51 | |
| 52 | mux.HandleFunc("/jsonp", func(w http.ResponseWriter, req *http.Request) { |
| 53 | r.JSONP(w, http.StatusOK, "callbackName", map[string]string{"hello": "jsonp"}) |
| 54 | }) |
| 55 | |
| 56 | mux.HandleFunc("/xml", func(w http.ResponseWriter, req *http.Request) { |
| 57 | r.XML(w, http.StatusOK, ExampleXml{One: "hello", Two: "xml"}) |
| 58 | }) |
| 59 | |
| 60 | mux.HandleFunc("/html", func(w http.ResponseWriter, req *http.Request) { |
| 61 | // Assumes you have a template in ./templates called "example.tmpl" |
| 62 | // $ mkdir -p templates && echo "<h1>Hello {{.}}.</h1>" > templates/example.tmpl |
| 63 | r.HTML(w, http.StatusOK, "example", "World") |
| 64 | }) |
| 65 | |
| 66 | http.ListenAndServe("127.0.0.1:3000", mux) |
| 67 | } |
| 68 | ~~~ |
| 69 | |
| 70 | ~~~ html |
| 71 | <!-- templates/example.tmpl --> |
| 72 | <h1>Hello {{.}}.</h1> |
| 73 | ~~~ |
| 74 | |
| 75 | ### Available Options |
| 76 | Render comes with a variety of configuration options _(Note: these are not the default option values. See the defaults below.)_: |
| 77 | |
| 78 | ~~~ go |
| 79 | // ... |
| 80 | r := render.New(render.Options{ |
| 81 | Directory: "templates", // Specify what path to load the templates from. |
| 82 | FileSystem: &LocalFileSystem{}, // Specify filesystem from where files are loaded. |
| 83 | Asset: func(name string) ([]byte, error) { // Load from an Asset function instead of file. |
| 84 | return []byte("template content"), nil |
| 85 | }, |
| 86 | AssetNames: func() []string { // Return a list of asset names for the Asset function |
| 87 | return []string{"filename.tmpl"} |
| 88 | }, |
| 89 | Layout: "layout", // Specify a layout template. Layouts can call {{ yield }} to render the current template or {{ partial "css" }} to render a partial from the current template. |
| 90 | Extensions: []string{".tmpl", ".html"}, // Specify extensions to load for templates. |
| 91 | Funcs: []template.FuncMap{AppHelpers}, // Specify helper function maps for templates to access. |
| 92 | Delims: render.Delims{"{[{", "}]}"}, // Sets delimiters to the specified strings. |
| 93 | Charset: "UTF-8", // Sets encoding for content-types. Default is "UTF-8". |
| 94 | DisableCharset: true, // Prevents the charset from being appended to the content type header. |
| 95 | IndentJSON: true, // Output human readable JSON. |
| 96 | IndentXML: true, // Output human readable XML. |
| 97 | PrefixJSON: []byte(")]}',\n"), // Prefixes JSON responses with the given bytes. |
| 98 | PrefixXML: []byte("<?xml version='1.0' encoding='UTF-8'?>"), // Prefixes XML responses with the given bytes. |
| 99 | HTMLContentType: "application/xhtml+xml", // Output XHTML content type instead of default "text/html". |
| 100 | IsDevelopment: true, // Render will now recompile the templates on every HTML response. |
| 101 | UseMutexLock: true, // Overrides the default no lock implementation and uses the standard `sync.RWMutex` lock. |
| 102 | UnEscapeHTML: true, // Replace ensure '&<>' are output correctly (JSON only). |
| 103 | StreamingJSON: true, // Streams the JSON response via json.Encoder. |
| 104 | RequirePartials: true, // Return an error if a template is missing a partial used in a layout. |
| 105 | DisableHTTPErrorRendering: true, // Disables automatic rendering of http.StatusInternalServerError when an error occurs. |
| 106 | }) |
| 107 | // ... |
| 108 | ~~~ |
| 109 | |
| 110 | ### Default Options |
| 111 | These are the preset options for Render: |
| 112 | |
| 113 | ~~~ go |
| 114 | r := render.New() |
| 115 | |
| 116 | // Is the same as the default configuration options: |
| 117 | |
| 118 | r := render.New(render.Options{ |
| 119 | Directory: "templates", |
| 120 | FileSystem: &LocalFileSystem{}, |
| 121 | Asset: nil, |
| 122 | AssetNames: nil, |
| 123 | Layout: "", |
| 124 | Extensions: []string{".tmpl"}, |
| 125 | Funcs: []template.FuncMap{}, |
| 126 | Delims: render.Delims{"{{", "}}"}, |
| 127 | Charset: "UTF-8", |
| 128 | DisableCharset: false, |
| 129 | IndentJSON: false, |
| 130 | IndentXML: false, |
| 131 | PrefixJSON: []byte(""), |
| 132 | PrefixXML: []byte(""), |
| 133 | BinaryContentType: "application/octet-stream", |
| 134 | HTMLContentType: "text/html", |
| 135 | JSONContentType: "application/json", |
| 136 | JSONPContentType: "application/javascript", |
| 137 | TextContentType: "text/plain", |
| 138 | XMLContentType: "application/xhtml+xml", |
| 139 | IsDevelopment: false, |
| 140 | UseMutexLock: false, |
| 141 | UnEscapeHTML: false, |
| 142 | StreamingJSON: false, |
| 143 | RequirePartials: false, |
| 144 | DisableHTTPErrorRendering: false, |
| 145 | RenderPartialsWithoutPrefix: false, |
| 146 | BufferPool: GenericBufferPool, |
| 147 | }) |
| 148 | ~~~ |
| 149 | |
| 150 | ### JSON vs Streaming JSON |
| 151 | By default, Render does **not** stream JSON to the `http.ResponseWriter`. It instead marshalls your object into a byte array, and if no errors occurred, writes that byte array to the `http.ResponseWriter`. If you would like to use the built it in streaming functionality (`json.Encoder`), you can set the `StreamingJSON` setting to `true`. This will stream the output directly to the `http.ResponseWriter`. Also note that streaming is only implemented in `render.JSON` and not `render.JSONP`, and the `UnEscapeHTML` and `Indent` options are ignored when streaming. |
| 152 | |
| 153 | ### Loading Templates |
| 154 | By default Render will attempt to load templates with a '.tmpl' extension from the "templates" directory. Templates are found by traversing the templates directory and are named by path and basename. For instance, the following directory structure: |
| 155 | |
| 156 | ~~~ |
| 157 | templates/ |
| 158 | | |
| 159 | |__ admin/ |
| 160 | | | |
| 161 | | |__ index.tmpl |
| 162 | | | |
| 163 | | |__ edit.tmpl |
| 164 | | |
| 165 | |__ home.tmpl |
| 166 | ~~~ |
| 167 | |
| 168 | Will provide the following templates: |
| 169 | ~~~ |
| 170 | admin/index |
| 171 | admin/edit |
| 172 | home |
| 173 | ~~~ |
| 174 | |
| 175 | Templates can be loaded from an `embed.FS`. |
| 176 | |
| 177 | ~~~ go |
| 178 | // ... |
| 179 | |
| 180 | //go:embed templates/*.html templates/*.tmpl |
| 181 | var embeddedTemplates embed.FS |
| 182 | |
| 183 | // ... |
| 184 | |
| 185 | r := render.New(render.Options{ |
| 186 | Directory: "templates", |
| 187 | FileSystem: &render.EmbedFileSystem{ |
| 188 | FS: embeddedTemplates, |
| 189 | }, |
| 190 | Extensions: []string{".html", ".tmpl"}, |
| 191 | }) |
| 192 | // ... |
| 193 | ~~~ |
| 194 | |
| 195 | You can also load templates from memory by providing the `Asset` and `AssetNames` options, |
| 196 | e.g. when generating an asset file using [go-bindata](https://github.com/jteeuwen/go-bindata). |
| 197 | |
| 198 | ### Layouts |
| 199 | Render provides `yield` and `partial` functions for layouts to access: |
| 200 | ~~~ go |
| 201 | // ... |
| 202 | r := render.New(render.Options{ |
| 203 | Layout: "layout", |
| 204 | }) |
| 205 | // ... |
| 206 | ~~~ |
| 207 | |
| 208 | ~~~ html |
| 209 | <!-- templates/layout.tmpl --> |
| 210 | <html> |
| 211 | <head> |
| 212 | <title>My Layout</title> |
| 213 | <!-- Render the partial template called `css-$current_template` here --> |
| 214 | {{ partial "css" }} |
| 215 | </head> |
| 216 | <body> |
| 217 | <!-- render the partial template called `header-$current_template` here --> |
| 218 | {{ partial "header" }} |
| 219 | <!-- Render the current template here --> |
| 220 | {{ yield }} |
| 221 | <!-- render the partial template called `footer-$current_template` here --> |
| 222 | {{ partial "footer" }} |
| 223 | </body> |
| 224 | </html> |
| 225 | ~~~ |
| 226 | |
| 227 | `current` can also be called to get the current template being rendered. |
| 228 | ~~~ html |
| 229 | <!-- templates/layout.tmpl --> |
| 230 | <html> |
| 231 | <head> |
| 232 | <title>My Layout</title> |
| 233 | </head> |
| 234 | <body> |
| 235 | This is the {{ current }} page. |
| 236 | </body> |
| 237 | </html> |
| 238 | ~~~ |
| 239 | |
| 240 | Partials are defined by individual templates as seen below. The partial template's |
| 241 | name needs to be defined as "{partial name}-{template name}". |
| 242 | ~~~ html |
| 243 | <!-- templates/home.tmpl --> |
| 244 | {{ define "header-home" }} |
| 245 | <h1>Home</h1> |
| 246 | {{ end }} |
| 247 | |
| 248 | {{ define "footer-home"}} |
| 249 | <p>The End</p> |
| 250 | {{ end }} |
| 251 | ~~~ |
| 252 | |
| 253 | By default, the template is not required to define all partials referenced in the |
| 254 | layout. If you want an error to be returned when a template does not define a |
| 255 | partial, set `Options.RequirePartials = true`. |
| 256 | |
| 257 | ### Character Encodings |
| 258 | Render will automatically set the proper Content-Type header based on which function you call. See below for an example of what the default settings would output (note that UTF-8 is the default, and binary data does not output the charset): |
| 259 | ~~~ go |
| 260 | // main.go |
| 261 | package main |
| 262 | |
| 263 | import ( |
| 264 | "encoding/xml" |
| 265 | "net/http" |
| 266 | |
| 267 | "github.com/unrolled/render" |
| 268 | ) |
| 269 | |
| 270 | type ExampleXml struct { |
| 271 | XMLName xml.Name `xml:"example"` |
| 272 | One string `xml:"one,attr"` |
| 273 | Two string `xml:"two,attr"` |
| 274 | } |
| 275 | |
| 276 | func main() { |
| 277 | r := render.New(render.Options{}) |
| 278 | mux := http.NewServeMux() |
| 279 | |
| 280 | // This will set the Content-Type header to "application/octet-stream". |
| 281 | // Note that this does not receive a charset value. |
| 282 | mux.HandleFunc("/data", func(w http.ResponseWriter, req *http.Request) { |
| 283 | r.Data(w, http.StatusOK, []byte("Some binary data here.")) |
| 284 | }) |
| 285 | |
| 286 | // This will set the Content-Type header to "application/json; charset=UTF-8". |
| 287 | mux.HandleFunc("/json", func(w http.ResponseWriter, req *http.Request) { |
| 288 | r.JSON(w, http.StatusOK, map[string]string{"hello": "json"}) |
| 289 | }) |
| 290 | |
| 291 | // This will set the Content-Type header to "text/xml; charset=UTF-8". |
| 292 | mux.HandleFunc("/xml", func(w http.ResponseWriter, req *http.Request) { |
| 293 | r.XML(w, http.StatusOK, ExampleXml{One: "hello", Two: "xml"}) |
| 294 | }) |
| 295 | |
| 296 | // This will set the Content-Type header to "text/plain; charset=UTF-8". |
| 297 | mux.HandleFunc("/text", func(w http.ResponseWriter, req *http.Request) { |
| 298 | r.Text(w, http.StatusOK, "Plain text here") |
| 299 | }) |
| 300 | |
| 301 | // This will set the Content-Type header to "text/html; charset=UTF-8". |
| 302 | mux.HandleFunc("/html", func(w http.ResponseWriter, req *http.Request) { |
| 303 | // Assumes you have a template in ./templates called "example.tmpl" |
| 304 | // $ mkdir -p templates && echo "<h1>Hello {{.}}.</h1>" > templates/example.tmpl |
| 305 | r.HTML(w, http.StatusOK, "example", "World") |
| 306 | }) |
| 307 | |
| 308 | http.ListenAndServe("127.0.0.1:3000", mux) |
| 309 | } |
| 310 | ~~~ |
| 311 | |
| 312 | In order to change the charset, you can set the `Charset` within the `render.Options` to your encoding value: |
| 313 | ~~~ go |
| 314 | // main.go |
| 315 | package main |
| 316 | |
| 317 | import ( |
| 318 | "encoding/xml" |
| 319 | "net/http" |
| 320 | |
| 321 | "github.com/unrolled/render" |
| 322 | ) |
| 323 | |
| 324 | type ExampleXml struct { |
| 325 | XMLName xml.Name `xml:"example"` |
| 326 | One string `xml:"one,attr"` |
| 327 | Two string `xml:"two,attr"` |
| 328 | } |
| 329 | |
| 330 | func main() { |
| 331 | r := render.New(render.Options{ |
| 332 | Charset: "ISO-8859-1", |
| 333 | }) |
| 334 | mux := http.NewServeMux() |
| 335 | |
| 336 | // This will set the Content-Type header to "application/octet-stream". |
| 337 | // Note that this does not receive a charset value. |
| 338 | mux.HandleFunc("/data", func(w http.ResponseWriter, req *http.Request) { |
| 339 | r.Data(w, http.StatusOK, []byte("Some binary data here.")) |
| 340 | }) |
| 341 | |
| 342 | // This will set the Content-Type header to "application/json; charset=ISO-8859-1". |
| 343 | mux.HandleFunc("/json", func(w http.ResponseWriter, req *http.Request) { |
| 344 | r.JSON(w, http.StatusOK, map[string]string{"hello": "json"}) |
| 345 | }) |
| 346 | |
| 347 | // This will set the Content-Type header to "text/xml; charset=ISO-8859-1". |
| 348 | mux.HandleFunc("/xml", func(w http.ResponseWriter, req *http.Request) { |
| 349 | r.XML(w, http.StatusOK, ExampleXml{One: "hello", Two: "xml"}) |
| 350 | }) |
| 351 | |
| 352 | // This will set the Content-Type header to "text/plain; charset=ISO-8859-1". |
| 353 | mux.HandleFunc("/text", func(w http.ResponseWriter, req *http.Request) { |
| 354 | r.Text(w, http.StatusOK, "Plain text here") |
| 355 | }) |
| 356 | |
| 357 | // This will set the Content-Type header to "text/html; charset=ISO-8859-1". |
| 358 | mux.HandleFunc("/html", func(w http.ResponseWriter, req *http.Request) { |
| 359 | // Assumes you have a template in ./templates called "example.tmpl" |
| 360 | // $ mkdir -p templates && echo "<h1>Hello {{.}}.</h1>" > templates/example.tmpl |
| 361 | r.HTML(w, http.StatusOK, "example", "World") |
| 362 | }) |
| 363 | |
| 364 | http.ListenAndServe("127.0.0.1:3000", mux) |
| 365 | } |
| 366 | ~~~ |
| 367 | |
| 368 | ### Error Handling |
| 369 | |
| 370 | The rendering functions return any errors from the rendering engine. |
| 371 | By default, they will also write the error to the HTTP response and set the status code to 500. You can disable |
| 372 | this behavior so that you can handle errors yourself by setting |
| 373 | `Options.DisableHTTPErrorRendering: true`. |
| 374 | |
| 375 | ~~~go |
| 376 | r := render.New(render.Options{ |
| 377 | DisableHTTPErrorRendering: true, |
| 378 | }) |
| 379 | |
| 380 | //... |
| 381 | |
| 382 | err := r.HTML(w, http.StatusOK, "example", "World") |
| 383 | if err != nil{ |
| 384 | http.Redirect(w, r, "/my-custom-500", http.StatusFound) |
| 385 | } |
| 386 | ~~~ |
| 387 | |
| 388 | ## Integration Examples |
| 389 | |
| 390 | ### [Echo](https://github.com/labstack/echo) |
| 391 | ~~~ go |
| 392 | // main.go |
| 393 | package main |
| 394 | |
| 395 | import ( |
| 396 | "io" |
| 397 | "net/http" |
| 398 | |
| 399 | "github.com/labstack/echo" |
| 400 | "github.com/unrolled/render" |
| 401 | ) |
| 402 | |
| 403 | type RenderWrapper struct { // We need to wrap the renderer because we need a different signature for echo. |
| 404 | rnd *render.Render |
| 405 | } |
| 406 | |
| 407 | func (r *RenderWrapper) Render(w io.Writer, name string, data interface{},c echo.Context) error { |
| 408 | return r.rnd.HTML(w, 0, name, data) // The zero status code is overwritten by echo. |
| 409 | } |
| 410 | |
| 411 | func main() { |
| 412 | r := &RenderWrapper{render.New()} |
| 413 | |
| 414 | e := echo.New() |
| 415 | |
| 416 | e.Renderer = r |
| 417 | |
| 418 | e.GET("/", func(c echo.Context) error { |
| 419 | return c.Render(http.StatusOK, "TemplateName", "TemplateData") |
| 420 | }) |
| 421 | |
| 422 | e.Logger.Fatal(e.Start("127.0.0.1:8080")) |
| 423 | } |
| 424 | ~~~ |
| 425 | |
| 426 | ### [Gin](https://github.com/gin-gonic/gin) |
| 427 | ~~~ go |
| 428 | // main.go |
| 429 | package main |
| 430 | |
| 431 | import ( |
| 432 | "net/http" |
| 433 | |
| 434 | "github.com/gin-gonic/gin" |
| 435 | "github.com/unrolled/render" |
| 436 | ) |
| 437 | |
| 438 | func main() { |
| 439 | r := render.New(render.Options{ |
| 440 | IndentJSON: true, |
| 441 | }) |
| 442 | |
| 443 | router := gin.Default() |
| 444 | |
| 445 | router.GET("/", func(c *gin.Context) { |
| 446 | r.JSON(c.Writer, http.StatusOK, map[string]string{"welcome": "This is rendered JSON!"}) |
| 447 | }) |
| 448 | |
| 449 | router.Run("127.0.0.1:8080") |
| 450 | } |
| 451 | ~~~ |
| 452 | |
| 453 | ### [Goji](https://github.com/zenazn/goji) |
| 454 | ~~~ go |
| 455 | // main.go |
| 456 | package main |
| 457 | |
| 458 | import ( |
| 459 | "net/http" |
| 460 | |
| 461 | "github.com/zenazn/goji" |
| 462 | "github.com/zenazn/goji/web" |
| 463 | "github.com/unrolled/render" |
| 464 | ) |
| 465 | |
| 466 | func main() { |
| 467 | r := render.New(render.Options{ |
| 468 | IndentJSON: true, |
| 469 | }) |
| 470 | |
| 471 | goji.Get("/", func(c web.C, w http.ResponseWriter, req *http.Request) { |
| 472 | r.JSON(w, http.StatusOK, map[string]string{"welcome": "This is rendered JSON!"}) |
| 473 | }) |
| 474 | goji.Serve() // Defaults to ":8000". |
| 475 | } |
| 476 | ~~~ |
| 477 | |
| 478 | ### [Negroni](https://github.com/codegangsta/negroni) |
| 479 | ~~~ go |
| 480 | // main.go |
| 481 | package main |
| 482 | |
| 483 | import ( |
| 484 | "net/http" |
| 485 | |
| 486 | "github.com/urfave/negroni" |
| 487 | "github.com/unrolled/render" |
| 488 | ) |
| 489 | |
| 490 | func main() { |
| 491 | r := render.New(render.Options{ |
| 492 | IndentJSON: true, |
| 493 | }) |
| 494 | mux := http.NewServeMux() |
| 495 | |
| 496 | mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { |
| 497 | r.JSON(w, http.StatusOK, map[string]string{"welcome": "This is rendered JSON!"}) |
| 498 | }) |
| 499 | |
| 500 | n := negroni.Classic() |
| 501 | n.UseHandler(mux) |
| 502 | n.Run("127.0.0.1:8080") |
| 503 | } |
| 504 | ~~~ |
| 505 | |
| 506 | ### [Traffic](https://github.com/pilu/traffic) |
| 507 | ~~~ go |
| 508 | // main.go |
| 509 | package main |
| 510 | |
| 511 | import ( |
| 512 | "net/http" |
| 513 | |
| 514 | "github.com/pilu/traffic" |
| 515 | "github.com/unrolled/render" |
| 516 | ) |
| 517 | |
| 518 | func main() { |
| 519 | r := render.New(render.Options{ |
| 520 | IndentJSON: true, |
| 521 | }) |
| 522 | |
| 523 | router := traffic.New() |
| 524 | router.Get("/", func(w traffic.ResponseWriter, req *traffic.Request) { |
| 525 | r.JSON(w, http.StatusOK, map[string]string{"welcome": "This is rendered JSON!"}) |
| 526 | }) |
| 527 | |
| 528 | router.Run() // Defaults to "127.0.0.1:3000". |
| 529 | } |
| 530 | ~~~ |