Giter Site home page Giter Site logo

go-template's Introduction

Build Status https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg 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 github.com/kataras/go-template

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 (
	"github.com/kataras/go-template/amber"
	"github.com/kataras/go-template/html"
	"github.com/kataras/iris"
)

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 (
	"github.com/kataras/go-template"
	"github.com/kataras/go-template/amber"
	"github.com/kataras/go-template/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.5

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.

go-template's People

Contributors

kataras avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.