render

package
v0.0.140 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 22, 2015 License: MIT, GPL-2.0 Imports: 13 Imported by: 0

README

render wercker status

Martini middleware/handler for easily rendering serialized JSON, XML, and HTML template responses.

API Reference

Usage

render uses Go's html/template package to render html templates.

// main.go
package main

import (
  "github.com/go-martini/martini"
  "github.com/martini-contrib/render"
)

func main() {
  m := martini.Classic()
  // render html templates from templates directory
  m.Use(render.Renderer())

  m.Get("/", func(r render.Render) {
    r.HTML(200, "hello", "jeremy")
  })

  m.Run()
}

<!-- templates/hello.tmpl -->
<h2>Hello {{.}}!</h2>
Options

render.Renderer comes with a variety of configuration options:

// ...
m.Use(render.Renderer(render.Options{
  Directory: "templates", // Specify what path to load the templates from.
  Layout: "layout", // Specify a layout template. Layouts can call {{ yield }} to render the current template.
  Extensions: []string{".tmpl", ".html"}, // Specify extensions to load for templates.
  Funcs: []template.FuncMap{AppHelpers}, // Specify helper function maps for templates to access.
  Delims: render.Delims{"{[{", "}]}"}, // Sets delimiters to the specified strings.
  Charset: "UTF-8", // Sets encoding for json and html content-types. Default is "UTF-8".
  IndentJSON: true, // Output human readable JSON
  IndentXML: true, // Output human readable XML
  HTMLContentType: "application/xhtml+xml", // Output XHTML content type instead of default "text/html"
}))
// ...
Loading Templates

By default the render.Renderer middleware 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:

templates/
  |
  |__ admin/
  |      |
  |      |__ index.tmpl
  |      |
  |      |__ edit.tmpl
  |
  |__ home.tmpl

Will provide the following templates:

admin/index
admin/edit
home
Layouts

render.Renderer provides a yield function for layouts to access:

// ...
m.Use(render.Renderer(render.Options{
  Layout: "layout",
}))
// ...
<!-- templates/layout.tmpl -->
<html>
  <head>
    <title>Martini Plz</title>
  </head>
  <body>
    <!-- Render the current template here -->
    {{ yield }}
  </body>
</html>

current can also be called to get the current template being rendered.

<!-- templates/layout.tmpl -->
<html>
  <head>
    <title>Martini Plz</title>
  </head>
  <body>
    This is the {{ current }} page.
  </body>
</html>
Character Encodings

The render.Renderer middleware 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):

// main.go
package main

import (
  "encoding/xml"

  "github.com/go-martini/martini"
  "github.com/martini-contrib/render"
)

type Greeting struct {
  XMLName xml.Name `xml:"greeting"`
  One     string   `xml:"one,attr"`
  Two     string   `xml:"two,attr"`
}

func main() {
  m := martini.Classic()
  m.Use(render.Renderer())

  // This will set the Content-Type header to "text/html; charset=UTF-8"
  m.Get("/", func(r render.Render) {
    r.HTML(200, "hello", "world")
  })

  // This will set the Content-Type header to "application/json; charset=UTF-8"
  m.Get("/api", func(r render.Render) {
    r.JSON(200, map[string]interface{}{"hello": "world"})
  })

  // This will set the Content-Type header to "text/xml; charset=UTF-8"
  m.Get("/xml", func(r render.Render) {
    r.XML(200, Greeting{One: "hello", Two: "world"})
  })

  // This will set the Content-Type header to "text/plain; charset=UTF-8"
  m.Get("/text", func(r render.Render) {
    r.Text(200, "hello, world")
  })

  m.Run()
}

In order to change the charset, you can set the Charset within the render.Options to your encoding value:

// main.go
package main

import (
  "encoding/xml"

  "github.com/go-martini/martini"
  "github.com/martini-contrib/render"
)

type Greeting struct {
  XMLName xml.Name `xml:"greeting"`
  One     string   `xml:"one,attr"`
  Two     string   `xml:"two,attr"`
}

func main() {
  m := martini.Classic()
  m.Use(render.Renderer(render.Options{
    Charset: "ISO-8859-1",
  }))

  // This will set the Content-Type header to "text/html; charset=ISO-8859-1"
  m.Get("/", func(r render.Render) {
    r.HTML(200, "hello", "world")
  })

  // This will set the Content-Type header to "application/json; charset=ISO-8859-1"
  m.Get("/api", func(r render.Render) {
    r.JSON(200, map[string]interface{}{"hello": "world"})
  })

  // This will set the Content-Type header to "text/xml; charset=ISO-8859-1"
  m.Get("/xml", func(r render.Render) {
    r.XML(200, Greeting{One: "hello", Two: "world"})
  })

  // This will set the Content-Type header to "text/plain; charset=ISO-8859-1"
  m.Get("/text", func(r render.Render) {
    r.Text(200, "hello, world")
  })

  m.Run()
}

Authors

Documentation

Overview

Package render is a middleware for Martini that provides easy JSON serialization and HTML template rendering.

package main

import (
  "encoding/xml"

  "github.com/go-martini/martini"
  "github.com/martini-contrib/render"
)

type Greeting struct {
  XMLName xml.Name `xml:"greeting"`
  One     string   `xml:"one,attr"`
  Two     string   `xml:"two,attr"`
}

func main() {
  m := martini.Classic()
  m.Use(render.Renderer()) // reads "templates" directory by default

  m.Get("/html", func(r render.Render) {
    r.HTML(200, "mytemplate", nil)
  })

  m.Get("/json", func(r render.Render) {
    r.JSON(200, "hello world")
  })

  m.Get("/xml", func(r render.Render) {
    r.XML(200, Greeting{One: "hello", Two: "world"})
  })

  m.Run()
}

Index

Constants

View Source
const (
	ContentType   = "Content-Type"
	ContentLength = "Content-Length"
	ContentBinary = "application/octet-stream"
	ContentText   = "text/plain"
	ContentJSON   = "application/json"
	ContentHTML   = "text/html"
	ContentXHTML  = "application/xhtml+xml"
	ContentXML    = "text/xml"
)

Variables

This section is empty.

Functions

func Renderer

func Renderer(options ...Options) martini.Handler

Renderer is a Middleware that maps a render.Render service into the Martini handler chain. An single variadic render.Options struct can be optionally provided to configure HTML rendering. The default directory for templates is "templates" and the default file extension is ".tmpl".

If MARTINI_ENV is set to "" or "development" then templates will be recompiled on every request. For more performance, set the MARTINI_ENV environment variable to "production"

Types

type Delims

type Delims struct {
	// Left delimiter, defaults to {{
	Left string
	// Right delimiter, defaults to }}
	Right string
}

Delims represents a set of Left and Right delimiters for HTML template rendering

type HTMLOptions

type HTMLOptions struct {
	// Layout template name. Overrides Options.Layout.
	Layout string
}

HTMLOptions is a struct for overriding some rendering Options for specific HTML call

type Options

type Options struct {
	// Directory to load templates. Default is "templates"
	Directory string
	// Layout template name. Will not render a layout if "". Defaults to "".
	Layout string
	// Extensions to parse template files from. Defaults to [".tmpl"]
	Extensions []string
	// Funcs is a slice of FuncMaps to apply to the template upon compilation. This is useful for helper functions. Defaults to [].
	Funcs []template.FuncMap
	// Delims sets the action delimiters to the specified strings in the Delims struct.
	Delims Delims
	// Appends the given charset to the Content-Type header. Default is "UTF-8".
	Charset string
	// Outputs human readable JSON
	IndentJSON bool
	// Outputs human readable XML
	IndentXML bool
	// Prefixes the JSON output with the given bytes.
	PrefixJSON []byte
	// Prefixes the XML output with the given bytes.
	PrefixXML []byte
	// Allows changing of output to XHTML instead of HTML. Default is "text/html"
	HTMLContentType string
}

Options is a struct for specifying configuration options for the render.Renderer middleware

type Render

type Render interface {
	// JSON writes the given status and JSON serialized version of the given value to the http.ResponseWriter.
	JSON(status int, v interface{})
	// HTML renders a html template specified by the name and writes the result and given status to the http.ResponseWriter.
	HTML(status int, name string, v interface{}, htmlOpt ...HTMLOptions)
	// XML writes the given status and XML serialized version of the given value to the http.ResponseWriter.
	XML(status int, v interface{})
	// Data writes the raw byte array to the http.ResponseWriter.
	Data(status int, v []byte)
	// Text writes the given status and plain text to the http.ResponseWriter.
	Text(status int, v string)
	// Error is a convenience function that writes an http status to the http.ResponseWriter.
	Error(status int)
	// Status is an alias for Error (writes an http status to the http.ResponseWriter)
	Status(status int)
	// Redirect is a convienience function that sends an HTTP redirect. If status is omitted, uses 302 (Found)
	Redirect(location string, status ...int)
	// Template returns the internal *template.Template used to render the HTML
	Template() *template.Template
	// Header exposes the header struct from http.ResponseWriter.
	Header() http.Header
}

Render is a service that can be injected into a Martini handler. Render provides functions for easily writing JSON and HTML templates out to a http Response.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL