template

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2016 License: MIT Imports: 5 Imported by: 16

README

Build Status Report card License Releases Read me docs Chat Built with GoLang

The package go-template provides the easier way to use templates via template engine, supports multiple template engines with different file extensions.

It's a cross-framework means that it's 100% compatible with standard net/http, iris & fasthttp

6 template engines are supported:

  • standard html/template
  • amber
  • django
  • handlebars
  • pug(jade)
  • markdown

It's already tested on production & used on Iris and Q web framework.

Installation

The only requirement is the Go Programming Language, at least v1.7.

$ go get -u gopkg.in/kataras/go-template.v0

Examples

Run them from the /examples folder.

Otherwise, you can view examples via Iris example's repository here.

Read the kataras/iris/template.go to see how Iris uses this package.

Docs

Read the godocs.

Iris Quick look

Iris is the fastest web framework for Go, so far. It's based on fasthttp, check that out if you didn't yet.

Examples covers the big picture, this is just a small code overview*

Make sure that you read & run the iris-contrib/examples/template_engines to cover the Iris + go-template part.

package main

import (
	"gopkg.in/kataras/go-template.v0/amber"
	"gopkg.in/kataras/go-template.v0/html"
	"gopkg.in/kataras/iris.v4"
)

type mypage struct {
	Title   string
	Message string
}

func main() {

	iris.UseTemplate(html.New()) // the Iris' default if no template engines are setted.

	// add our second template engine with the same directory but with .amber file extension
	iris.UseTemplate(amber.New(amber.Config{})).Directory("./templates", ".amber")

	iris.Get("/render_html", func(ctx *iris.Context) {
		ctx.RenderWithStatus(iris.StatusOK, "hiHTML.html", map[string]interface{}{"Name": "You!"})
	})

	iris.Get("/render_amber", func(ctx *iris.Context) {
		ctx.MustRender("hiAMBER.amber", map[string]interface{}{"Name": "You!"})
	})

	println("Open a browser tab & go to localhost:8080/render_html  & localhost:8080/render_amber")
	iris.Listen(":8080")
}


NET/HTTP Quick look

// Package main uses the template.Mux here to simplify the steps
// and support of loading more than one template engine for a single app
// you can do the same things without the Mux, as you saw on the /html example folder
package main

import (
	"gopkg.in/kataras/go-template.v0"
	"gopkg.in/kataras/go-template.v0/amber"
	"gopkg.in/kataras/go-template.v0/html"
	"net/http"
)

type mypage struct {
	Title   string
	Message string
}

func main() {

	// templates := template.NewMux()
	// templates.AddEngine(html.New()).Directory("./templates", ".html") // the defaults
	// or just use the default package-level mux:
	template.AddEngine(html.New())

	// add our second template engine with the same directory but with .amber file extension
	template.AddEngine(amber.New()).Directory("./templates", ".amber")

	// load all the template files using the correct template engine for each one of the files
	err := template.Load()
	if err != nil {
		panic("While parsing the template files: " + err.Error())
	}

	http.Handle("/render_html", http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
		// first parameter the writer
		// second parameter any page context (look ./templates/mypage.html) and you will understand
		// third parameter is optionally, is a map[string]interface{}
		// which you can pass a "layout" to change the layout for this specific render action
		// or the "charset" to change the defaults which is "utf-8"

		// Does the same thing but returns the parsed template file results as string
		// useful when you want to send rich e-mails with a template
		// template.ExecuteString(name, pageContext, options...)

		err := template.ExecuteWriter(res, "hiHTML.html", map[string]interface{}{"Name": "You!"}) // yes you can pass simple maps instead of structs
		if err != nil {
			res.Write([]byte(err.Error()))
		}
	}))

	http.Handle("/render_amber", http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
		template.ExecuteWriter(res, "hiAMBER.amber", map[string]interface{}{"Name": "You!"})
	}))

	println("Open a browser tab & go to localhost:8080/render_html  & localhost:8080/render_amber")
	http.ListenAndServe(":8080", nil)
}


Note: All template engines have optional configuration which can be passed within $engine.New($engine.Config{})

FAQ

  • Q: Did this package works only with net/http ?

  • A: No, this package can work with Iris & fasthttp too, look here for more.

  • Q: How can I make my own template engine?

  • A: Simply, you have to implement only 3 functions, for load and execute the templates. One optionally (Funcs() map[string]interface{}) which is used to register any SharedFuncs. The simplest implementation, which you can look as example, is the Markdown Engine, which is located here.


type (
	// Engine the interface that all template engines must implement
	Engine interface {
		// LoadDirectory builds the templates, usually by directory and extension but these are engine's decisions
		LoadDirectory(directory string, extension string) error
		// LoadAssets loads the templates by binary
		// assetFn is a func which returns bytes, use it to load the templates by binary
		// namesFn returns the template filenames
		LoadAssets(virtualDirectory string, virtualExtension string, assetFn func(name string) ([]byte, error), namesFn func() []string) error

		// ExecuteWriter finds, execute a template and write its result to the out writer
		// options are the optional runtime options can be passed by user
		// an example of this is the "layout" or "gzip" option
		ExecuteWriter(out io.Writer, name string, binding interface{}, options ...map[string]interface{}) error
	}

	// EngineFuncs is optional interface for the Engine
	// used to insert the Iris' standard funcs, see var 'usedFuncs'
	EngineFuncs interface {
		// Funcs should returns the context or the funcs,
		// this property is used in order to register the iris' helper funcs
		Funcs() map[string]interface{}
	}

	// EngineRawExecutor is optional interface for the Engine
	// used to receive and parse a raw template string instead of a filename
	EngineRawExecutor interface {
		// ExecuteRaw is super-simple function without options and funcs, it's not used widely
		ExecuteRaw(src string, wr io.Writer, binding interface{}) error
	}
)

Explore these questions or navigate to the community chat.

Versioning

Current: v0.0.3

People

The author of go-template is @kataras.

If you're willing to donate, feel free to send any amount through paypal

Contributing

If you are interested in contributing to the go-template project, please make a PR.

License

This project is licensed under the MIT License.

License can be found here.

Documentation

Overview

Package template provides the easier way to use templates via template engine supports multiple template engines with different file extensions 6 template engines supported: standard html/template amber django handlebars pug(jade) markdown

Index

Constants

View Source
const NoLayout = "@.|.@no_layout@.|.@" // html/html.go. handlebars/handlebars.go. It's the same but the var is separated care for the future here.

NoLayout to disable layout for a particular template file

View Source
const (
	// Version current version number
	Version = "0.0.3"
)

Variables

View Source
var (
	// DefaultExtension the default file extension if empty setted
	DefaultExtension = ".html"
	// DefaultDirectory the default directory if empty setted
	DefaultDirectory = "." + string(os.PathSeparator) + "templates"
)

Functions

func ExecuteRaw

func ExecuteRaw(src string, wr io.Writer, binding interface{}) error

ExecuteRaw read moreon template.go:EngineRawParser parse with the first valid EngineRawParser

func ExecuteRawString

func ExecuteRawString(src string, binding interface{}) (result string, err error)

ExecuteRawString receives raw template source contents and returns it's result as string

func ExecuteString

func ExecuteString(name string, binding interface{}, options ...map[string]interface{}) (result string, err error)

ExecuteString executes a template from a specific template engine and returns its contents result as string, it doesn't renders

func ExecuteWriter

func ExecuteWriter(out io.Writer, name string, binding interface{}, options ...map[string]interface{}) (err error)

ExecuteWriter calls the correct template Engine's ExecuteWriter func

func GetCharsetOption

func GetCharsetOption(defaultValue string, options map[string]interface{}) string

GetCharsetOption receives a default value and the render options map and returns the correct charset for this render action

func GetGzipOption

func GetGzipOption(defaultValue bool, options map[string]interface{}) bool

GetGzipOption receives a default value and the render options map and returns if gzip is enabled for this render action

func Load

func Load() error

Load loads all template engines entries, returns the first error it just calls and returns the Entries.LoadALl

Types

type BinaryLoader

type BinaryLoader struct {
	*Loader
}

BinaryLoader optionally, called after EngineLocation's Directory, used when files are distrubuted inside the app executable sets the AssetFn and NamesFn

func (*BinaryLoader) Binary

func (t *BinaryLoader) Binary(assetFn func(name string) ([]byte, error), namesFn func() []string)

Binary optionally, called after Loader.Directory, used when files are distrubuted inside the app executable sets the AssetFn and NamesFn

type Engine

type Engine interface {
	// LoadDirectory builds the templates, usually by directory and extension but these are engine's decisions
	LoadDirectory(directory string, extension string) error
	// LoadAssets loads the templates by binary
	// assetFn is a func which returns bytes, use it to load the templates by binary
	// namesFn returns the template filenames
	LoadAssets(virtualDirectory string, virtualExtension string, assetFn func(name string) ([]byte, error), namesFn func() []string) error

	// ExecuteWriter finds, execute a template and write its result to the out writer
	// options are the optional runtime options can be passed by user and catched by the template engine when render
	// an example of this is the "layout" or "gzip" option
	ExecuteWriter(out io.Writer, name string, binding interface{}, options ...map[string]interface{}) error
}

Engine the interface that all template engines must implement

type EngineFuncs

type EngineFuncs interface {
	// Funcs should returns the context or the funcs,
	// this property is used in order to register any optional helper funcs
	Funcs() map[string]interface{}
}

EngineFuncs is optional interface for the Engine used to insert the helper funcs

type EngineRawExecutor

type EngineRawExecutor interface {
	// ExecuteRaw is super-simple function without options and funcs, it's not used widely
	ExecuteRaw(src string, wr io.Writer, binding interface{}) error
}

EngineRawExecutor is optional interface for the Engine used to receive and parse a raw template string instead of a filename

type Entries

type Entries []*Entry

Entries the template Engines with their loader

func (Entries) Find

func (entries Entries) Find(filename string) *Entry

Find receives a filename, gets its extension and returns the template engine responsible for that file extension

func (Entries) LoadAll

func (entries Entries) LoadAll() error

LoadAll loads all template engines entries, returns the first error

type Entry

type Entry struct {
	Loader *Loader
	Engine Engine
}

Entry contains a template Engine and its Loader

func (*Entry) LoadEngine

func (entry *Entry) LoadEngine() error

LoadEngine loads the Engine using its registered loader Internal Note: Loader can be used without a mux because of this we have this type of function here which just pass itself's field into other itself's field which, normally, is not a smart choice.

type Loader

type Loader struct {
	Dir       string
	Extension string
	// AssetFn and NamesFn used when files are distrubuted inside the app executable
	AssetFn func(name string) ([]byte, error)
	NamesFn func() []string
}

Loader contains the funcs to set the location for the templates by directory or by binary

func AddEngine

func AddEngine(e Engine) *Loader

AddEngine adds but not loads a template engine, returns the entry's Loader

func NewLoader

func NewLoader() *Loader

NewLoader returns a default Loader which is used to load template engine(s)

func (*Loader) Directory

func (t *Loader) Directory(dir string, fileExtension string) *BinaryLoader

Directory sets the directory to load from returns the Binary location which is optional

func (*Loader) IsBinary

func (t *Loader) IsBinary() bool

IsBinary returns true if .Binary is called and AssetFn and NamesFn are setted

func (*Loader) LoadEngine

func (t *Loader) LoadEngine(e Engine) error

LoadEngine receives a template Engine and calls its LoadAssets or the LoadDirectory with the loader's locations

type Mux

type Mux struct {
	// Reload reloads the template engine on each execute, used when the project is under development status
	// if true the template will reflect the runtime template files changes
	// defaults to false
	Reload bool

	// Entries the template Engines with their loader
	Entries Entries
	// SharedFuncs funcs that will be shared all over the supported template engines
	SharedFuncs map[string]interface{}
	// contains filtered or unexported fields
}

Mux is an optional feature, used when you want to use multiple template engines It stores the loaders with each of the template engine, the identifier of each template engine is the (loader's) Extension the registry finds the correct template engine and executes the template so you can use and render a template file by it's file extension

func NewMux

func NewMux(sharedFuncs ...map[string]interface{}) *Mux

NewMux returns a new Mux Mux is an optional feature, used when you want to use multiple template engines It stores the loaders with each of the template engine, the identifier of each template engine is the (loader's) Extension the registry finds the correct template engine and executes the template so you can use and render a template file by it's file extension

func (*Mux) AddEngine

func (m *Mux) AddEngine(e Engine) *Loader

AddEngine adds but not loads a template engine, returns the entry's Loader

func (*Mux) ExecuteRaw

func (m *Mux) ExecuteRaw(src string, wr io.Writer, binding interface{}) error

ExecuteRaw read moreon template.go:EngineRawParser parse with the first valid EngineRawParser

func (*Mux) ExecuteRawString

func (m *Mux) ExecuteRawString(src string, binding interface{}) (result string, err error)

ExecuteRawString receives raw template source contents and returns it's result as string

func (*Mux) ExecuteString

func (m *Mux) ExecuteString(name string, binding interface{}, options ...map[string]interface{}) (result string, err error)

ExecuteString executes a template from a specific template engine and returns its contents result as string, it doesn't renders

func (*Mux) ExecuteWriter

func (m *Mux) ExecuteWriter(out io.Writer, name string, binding interface{}, options ...map[string]interface{}) (err error)

ExecuteWriter calls the correct template Engine's ExecuteWriter func

func (*Mux) Load

func (m *Mux) Load() error

Load loads all template engines entries, returns the first error it just calls and returns the Entries.LoadALl

Directories

Path Synopsis
_examples
nethttp_html
Package main is a small example for html/template, same for all other
Package main is a small example for html/template, same for all other
nethttp_multi
Package main uses the template.Mux here to simplify the steps and support of loading more than one template engine for a single app you can do the same things without the Mux, as you saw on the /html example folder
Package main uses the template.Mux here to simplify the steps and support of loading more than one template engine for a single app you can do the same things without the Mux, as you saw on the /html example folder
Package handlebars the HandlebarsEngine's functionality
Package handlebars the HandlebarsEngine's functionality
Package pug the JadeEngine's functionality lives inside ../html now
Package pug the JadeEngine's functionality lives inside ../html now

Jump to

Keyboard shortcuts

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