view

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2019 License: MIT Imports: 10 Imported by: 0

README

View Renderer

GoDoc Build Status Coverage Status Go Report Card

A simple view renderer based on the html/template, but much simpler to use. Support layout rendering, including templates.

中文说明

Features

  • simple to use
  • support loading multiple directories, multiple files
  • support rendering string templates, etc.
  • support layout render.
    • eg {{ include "header" }} {{ yield }} {{ include "footer" }}
  • support include other templates. eg {{ include "other" }}
  • built-in some helper methods row, lower, upper, join ...

Godoc

Quick Start

package main

import (
	"bytes"
	"fmt"
	
	"github.com/gookit/view"
)

func main()  {
	// equals to call: view.NewRenderer() + r.MustInitialize()
	r := view.NewInitialized(func(r *view.Renderer) {
		// setting default layout
		r.Layout = "layout" // equals to "layout.tpl"
		// templates dir. will auto load on init.
		r.ViewsDir = "testdata"
		// add template function
		r.AddFunc("myFunc", func() string {
			return "my-func"
		})
	})

	// fmt.Println(r.TemplateNames(true))

	bf := new(bytes.Buffer)

	// render template string
	r.String(bf, `hello {{.}}`, "tom")
	fmt.Print(bf.String()) // hello tom

	// render template without layout
	r.Partial(bf, "home", "tom")
	bf.Reset()

	// render with default layout
	r.Render(bf, "home", "tom")
	bf.Reset()

	// render with custom layout
	r.Render(bf, "home", "tom", "site/layout")
	bf.Reset()
	
	// load named string template 
	r.LoadString("my-page", "welcome {{.}}")
	// now, you can use "my-page" as an template name
	r.Partial(bf, "my-page", "tom") // welcome tom
	bf.Reset()
	
	// more ways for load templates
	r.LoadByGlob("some/path/*", "some/path")
	r.LoadFiles("path/file1.tpl", "path/file2.tpl")
}

more API please GoDoc

Layout Example

basic layout structure:

{{ include "part0" }}{{ yield }}{{ include "part1" }}

current template will render at {{ yield }}

example files:

templates/
  |_ layouts/
  |    |_ default.tpl
  |    |_ header.tpl
  |    |_ footer.tpl
  |_ home.tpl
  |_ about.tpl
  • layout: templates/layouts/default.tpl
<html>
  <head>
    <title>layout example</title>
  </head>
  <body>
    <!-- include "layouts/header.tpl" -->
    {{ include "header" }}
    <!-- Render the current template here -->
    {{ yield }}
    <!-- include "layouts/footer.tpl" -->
    {{ include "footer" }}
  </body>
</html>
  • templates/layouts/header.tpl
<header>
    <h2>page header</h2>
</header>
  • templates/layouts/footer.tpl
<footer>
    <h2>page footer</h2>
</footer>
  • templates/home.tpl
  <h1>Hello, {{ .Name | upper }}</h1>
  <h2>At template {{ current }}</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
Usage
v := view.NewInitialized(func(r *view.Renderer) {
    // setting default layout
    r.Layout = "layouts/default" // equals to "layouts/default.tpl"
    // templates dir. will auto load on init.
    r.ViewsDir = "templates"
})

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
	v.Render(w, "home", view.M{"Name": "tom"})
})
log.Println("Listening port: 9100")
http.ListenAndServe(":9100", nil)

Available Options

// Debug setting
Debug bool
// Layout template name
Layout string
// Delims define for template
Delims TplDelims
// ViewsDir the default views directory
ViewsDir string
// ExtNames allowed template extensions. eg {"tpl", "html"}
ExtNames []string
// FuncMap func map for template
FuncMap template.FuncMap
// DisableLayout disable layout. default is False
DisableLayout bool
// AutoSearchFile auto search template file, when not found on compiled templates. default is False
AutoSearchFile bool
Apply options
  • method 1
r := NewRenderer()
r.Layout = "layouts/default"
// ... ...
r.MustInitialize()
  • method 2
r := NewRenderer(func (r *Renderer) {
	r.Layout = "layouts/default"
	// ... ...
})
r.MustInitialize()
  • method 3
r := NewInitialized(func (r *Renderer) {
	r.Layout = "layouts/default" 
	// ... ...
})

Reference

License

MIT

Documentation

Overview

Package view is a simple view renderer based on the `html/template`, but much simpler to use.

Source code and other details for the project are available at GitHub:

https://github.com/gookit/view

Usage please see example.

Example
// equals to call: view.NewRenderer() + r.MustInitialize()
r := NewInitialized(func(r *Renderer) {
	// setting default layout
	r.Layout = "layout" // equals to "layout.tpl"
	// templates dir. will auto load on init.
	r.ViewsDir = "testdata"
})

// fmt.Println(r.TemplateNames(true))

bf := new(bytes.Buffer)

// render template string
_ = r.String(bf, `hello {{.}}`, "tom")
fmt.Print(bf.String()) // hello tom

// render template without layout
_ = r.Partial(bf, "home", "tom")
bf.Reset()

// render with default layout
_ = r.Render(bf, "home", "tom")
bf.Reset()

// render with custom layout
_ = r.Render(bf, "home", "tom", "site/layout")
bf.Reset()

// load named template string
r.LoadString("my-page", "welcome {{.}}")
// now, you can use "my-page" as an template name
_ = r.Partial(bf, "my-page", "tom") // welcome tom
bf.Reset()

// more ways for load templates
r.LoadByGlob("some/path/*", "some/path")
r.LoadFiles("path/file1.tpl", "path/file2.tpl")
Output:

Index

Examples

Constants

View Source
const DefaultExt = ".tpl"

DefaultExt name

Variables

This section is empty.

Functions

func AddFunc added in v1.0.2

func AddFunc(name string, fn interface{})

AddFunc add template func

func AddFuncMap added in v1.0.2

func AddFuncMap(fm template.FuncMap)

AddFuncMap add template func map

func Execute added in v1.0.2

func Execute(w io.Writer, tplName string, v interface{}) error

Execute render partial, will not render layout file

func Initialize added in v1.0.2

func Initialize(fns ...func(r *Renderer))

Initialize the default instance

func LoadByGlob added in v1.0.2

func LoadByGlob(pattern string, baseDirs ...string)

LoadByGlob load templates by glob pattern.

func LoadFiles added in v1.0.2

func LoadFiles(files ...string)

LoadFiles load custom template files.

func LoadString added in v1.0.2

func LoadString(tplName string, tplString string)

LoadString load named template string.

func LoadStrings added in v1.0.2

func LoadStrings(sMap map[string]string)

LoadStrings load multi named template strings

func Partial added in v1.0.2

func Partial(w io.Writer, tplName string, v interface{}) error

Partial is alias of the Execute()

func Render added in v1.0.2

func Render(w io.Writer, tplName string, v interface{}, layouts ...string) error

Render a template name/file and write to the Writer.

func Revert added in v1.0.2

func Revert()

Revert the default instance

func String added in v1.0.2

func String(w io.Writer, tplString string, v interface{}) error

String render a template string

Types

type M

type M map[string]interface{}

M a short type for map[string]interface{}

type Renderer

type Renderer struct {

	// Debug setting
	Debug bool
	// Layout template name
	Layout string
	// Delims define for template
	Delims TplDelims
	// ViewsDir the default views directory
	ViewsDir string
	// ExtNames allowed template extensions. eg {"tpl", "html"}
	ExtNames []string
	// FuncMap func map for template
	FuncMap template.FuncMap
	// DisableLayout disable layout. default is False
	DisableLayout bool
	// AutoSearchFile
	// TODO: auto search template file, when not found on compiled templates. default is False
	AutoSearchFile bool
	// contains filtered or unexported fields
}

Renderer definition

func Default added in v1.0.2

func Default() *Renderer

Default get default instance

func NewInitialized

func NewInitialized(fns ...func(r *Renderer)) *Renderer

NewInitialized create a new and initialized view renderer

func NewRenderer

func NewRenderer(fns ...func(r *Renderer)) *Renderer

NewRenderer create a new view renderer

func (*Renderer) AddFunc

func (r *Renderer) AddFunc(name string, fn interface{})

AddFunc add template func

func (*Renderer) AddFuncMap

func (r *Renderer) AddFuncMap(fm template.FuncMap)

AddFuncMap add template func map

func (*Renderer) Execute added in v1.0.2

func (r *Renderer) Execute(w io.Writer, tplName string, v interface{}) error

Execute render partial, will not render layout file

func (*Renderer) Initialize

func (r *Renderer) Initialize() error

Initialize templates in the viewsDir, add do some prepare works. Notice: must call it on after create Renderer

func (*Renderer) IsValidExt

func (r *Renderer) IsValidExt(ext string) bool

IsValidExt check is valid ext name

func (*Renderer) LoadByGlob

func (r *Renderer) LoadByGlob(pattern string, baseDirs ...string)

LoadByGlob load templates by glob pattern. Usage:

r.LoadByGlob("views/*")
r.LoadByGlob("views/*.tpl") // add ext limit
r.LoadByGlob("views/**/*")

func (*Renderer) LoadFiles

func (r *Renderer) LoadFiles(files ...string)

LoadFiles load custom template files. Usage:

r.LoadFiles("path/file1.tpl", "path/file2.tpl")

func (*Renderer) LoadString

func (r *Renderer) LoadString(tplName string, tplString string)

LoadString load named template string. Usage:

r.LoadString("my-page", "welcome {{.}}")
// now, you can use "my-page" as an template name
r.Partial(w, "my-page", "tom") // welcome tom

func (*Renderer) LoadStrings

func (r *Renderer) LoadStrings(sMap map[string]string)

LoadStrings load multi named template strings

func (*Renderer) LoadedTemplates

func (r *Renderer) LoadedTemplates() []*template.Template

LoadedTemplates returns loaded template instances, including ROOT itself.

func (*Renderer) MustInitialize

func (r *Renderer) MustInitialize()

MustInitialize compile templates and report error

func (*Renderer) Partial

func (r *Renderer) Partial(w io.Writer, tplName string, v interface{}) error

Partial is alias of the Execute()

func (*Renderer) Render

func (r *Renderer) Render(w io.Writer, tplName string, v interface{}, layouts ...string) error

Render a template name/file and write to the Writer. Usage:

		renderer := view.NewRenderer()
 	// ... ...
		// will apply global layout setting
		renderer.Render(http.ResponseWriter, "user/login", data)
		// apply custom layout file
		renderer.Render(http.ResponseWriter, "user/login", data, "custom-layout")
		// will disable apply layout render
		renderer.Render(http.ResponseWriter, "user/login", data, "")

func (*Renderer) String

func (r *Renderer) String(w io.Writer, tplString string, v interface{}) error

String render a template string

func (*Renderer) Template

func (r *Renderer) Template(name string) *template.Template

Template get template instance by name

func (*Renderer) TemplateFiles

func (r *Renderer) TemplateFiles() map[string]string

TemplateFiles returns loaded template files

func (*Renderer) TemplateNames

func (r *Renderer) TemplateNames(format ...bool) string

TemplateNames returns loaded template names

func (*Renderer) Templates

func (r *Renderer) Templates() *template.Template

Templates returns root template instance

type TplDelims

type TplDelims struct {
	Left  string
	Right string
}

TplDelims for html template

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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