render

package module
v0.0.0-...-36d28ed Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2021 License: Apache-2.0 Imports: 13 Imported by: 0

README

go-render

This project is written by golang. Easily rendering serialized JSON, XML, and HTML template responses use http.ResponseWriter. It's migration from 'github.com/martini-contrib/render'

Usage

package main

import (
	"html/template"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"gitera.cn/ron/go-render"
)

func main() {
    var funcMap = template.FuncMap{
        "Add":        func(l, r int) int { return l + r },
        "FormatTime": func(t time.Time, str string) string { return util.NewDate().Format(t, str) },
    }

    // 初始化render
    render.Render(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.
        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
        FuncMap:    funcMap,                   // Functions add to template
        HTMLContentType: render.ContentHTML,   // Output XHTML content type instead of default "text/html"
    })

	r := gin.Default()
	// 添加路由
	r.GET("/", func(ctx *gin.Context) {
		// 设置参数
		d := map[string]template.HTML{
			"Title": "登陆",
		}

		// 渲染HTML
		render.HTML(ctx.Writer, 200, "index", d)
	})
	// 设置http服务
	s := &http.Server{
		Addr:           ":8080",
		Handler:        r,
		ReadTimeout:    30 * time.Second,
		WriteTimeout:   30 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	s.ListenAndServe()
}

The following templates:

<!-- templates/layout.tmpl -->
<!doctype html>
<html lang="zh">
<head>
<title>{{.Title}}</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
</head>
<body>
<!-- Render the current template here -->
{{ yield }}
</body>
</html>
<!-- templates/index.tmpl -->
<h1>{{.Name}}</h1>
<ul>
	<li>{{template "base/header"}}</li>
</ul>
<!-- templates/base/header.tmpl -->
<h2>我是头</h2>

Authors

Ron Zhang

Documentation

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 Data

func Data(w http.ResponseWriter, status int, v []byte)

func Error

func Error(w http.ResponseWriter, status int, v []byte)

Error writes the given HTTP status to the current ResponseWriter

func HTML

func HTML(w http.ResponseWriter, status int, name string, binding interface{}, htmlOptions ...HTMLOptions)

func Init

func Init(o Options)

Init is a external rendering. 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".

func JSON

func JSON(w http.ResponseWriter, status int, v interface{})

func Redirect

func Redirect(w http.ResponseWriter, r *http.Request, status int, location string)

func Render

func Render(o Options)

func Status

func Status(w http.ResponseWriter, status int)

func Template

func Template() *template.Template

func Text

func Text(w http.ResponseWriter, status int, v string)

func XML

func XML(w http.ResponseWriter, status int, v interface{})

Types

type Delimiter

type Delimiter struct {
	// Left delimiter, defaults to {{
	Left string `yaml:"Left"`
	// Right delimiter, defaults to }}
	Right string `yaml:"Right"`
}

Delimiter 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 `yaml:"Directory"`
	// Layout template name. Will not render a layout if "". Defaults to "".
	Layout string `yaml:"Layout"`
	// Extensions to parse template files from. Defaults to [".tmpl"]
	Extensions []string `yaml:"Extensions"`
	// Funcs is a slice of FuncMap to apply to the template upon compilation. This is useful for helper functions. Defaults to [].
	FuncMap template.FuncMap `yaml:"FuncMap"`
	// Delimiter sets the action delimiters to the specified strings in the Delimiter struct.
	Delimiter Delimiter `yaml:"Delimiter"`
	// Appends the given charset to the Content-Type header. Default is "UTF-8".
	Charset string `yaml:"Charset"`
	// Outputs human readable JSON
	IndentJSON bool `yaml:"IndentJSON"`
	// Outputs human readable XML
	IndentXML bool `yaml:"IndentXML"`
	// Prefixes the JSON output with the given bytes.
	PrefixJSON []byte `yaml:"PrefixJSON"`
	// Prefixes the XML output with the given bytes.
	PrefixXML []byte `yaml:"PrefixXML"`
	// Allows changing of output to XHTML instead of HTML. Default is "text/html"
	HTMLContentType string `yaml:"HTMLContentType"`
	// Initial BufferPool cap
	BufferPool int `yaml:"BufferPool"`
	// Set template in debug mode to refresh template.
	DebugMode bool `yaml:"DebugMode"`
}

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

Jump to

Keyboard shortcuts

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