easytpl

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 29, 2024 License: MIT Imports: 13 Imported by: 0

README

EasyTpl

GoDoc Coverage Status Go Report Card Unit-Tests

A simple template renderer based on the Go 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" }}
  • support extends base templates. eg {{ extends "base.tpl" }}
  • support custom template functions
  • built-in some helper methods row, lower, upper, join ...

Godoc

Quick Start

package main

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

func main()  {
	// equals to call: easytpl.NewRenderer() + r.MustInit()
	r := easytpl.NewInited(func(r *easytpl.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 APIs 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_tpl }}</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
Usage
v := easytpl.NewInited(func(r *easytpl.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", easytpl.M{"Name": "tom"})
})
slog.Println("Listening port: 9100")
http.ListenAndServe(":9100", nil)

extends example

A base template can be inherited using the {{ extends "base.tpl" }} statement.

Note: The extends statement must be on the first line of the template file

templates/
  |_ base.tpl
  |_ home.tpl
  |_ about.tpl

templates/base.tpl base template contents:

<html lang="en">
  <head>
    <title>layout example</title>
  </head>
  <body>
    {{ block "content" . }}
    <h1>Hello, at base template</h1>
    {{ end }}
  </body>
</html>

templates/home.tpl contents:

{{ extends "base" }}

{{ define "content" }}
  <h1>Hello, {{ .Name | upper }}</h1>
  <h2>At template {{ current_tpl }}</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
{{ end }}
Usage
package main

import (
    "net/http"
    
    "github.com/gookit/easytpl"
    "github.com/gookit/slog"
)

func main() {
    v := easytpl.NewExtends(easytpl.WithTplDirs("templates"))

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        v.Render(w, "home", easytpl.M{"Name": "tom"})
    })
    
    slog.Info("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, multi use "," split
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 := easytpl.NewRenderer()
r.Layout = "layouts/default"
// ... ...
r.MustInit()
  • method 2
r := easytpl.NewRenderer(func (r *Renderer) {
	r.Layout = "layouts/default"
	// ... ...
})
r.MustInit()
  • method 3
r := easytpl.NewInited(func (r *Renderer) {
	r.Layout = "layouts/default" 
	// ... ...
})

Reference

License

MIT

Documentation

Overview

Package easytpl is a simple template 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/easytpl

Usage please see example and README.

Example
package main

import (
	"bytes"
	"fmt"

	"github.com/gookit/easytpl"
)

func main() {
	// equals to call: easytpl.NewRenderer() + r.MustInit()
	r := easytpl.NewInited(func(r *easytpl.Renderer) {
		// setting default layout
		r.Layout = "layout" // equals to "layout.tpl"
		// root dir. will autoload on init.
		r.ViewsDir = "testdata/layouts"
	})

	// 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 a template name
	_ = r.Partial(bf, "my-page", "tom") // welcome tom
	bf.Reset()

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

Example (Extends)
package main

import (
	"fmt"
	"os"

	"github.com/gookit/easytpl"
)

func main() {
	r := easytpl.NewExtends()
	// load root
	r.LoadStrings(map[string]string{
		// layout template file
		"layout.tpl": `{{ block "header" . }}header{{ end }}
{{ block "body" . }}default{{ end }}
{{ block "footer" . }}footer{{ end }}`,
		// current page template
		"home.tpl": `{{ extends "layout.tpl" }}
{{ define "body" }}hello {{.}}{{ end }}`,
	})

	fmt.Println("- render 'layout.tpl'")
	err := r.Execute(os.Stdout, "layout.tpl", "inhere")
	if err != nil {
		panic(err)
	}

	fmt.Println("\n- render 'home.tpl'")
	err = r.Execute(os.Stdout, "home.tpl", "inhere")
	if err != nil {
		panic(err)
	}

}
Output:

- render 'layout.tpl'
header
default
footer
- render 'home.tpl'
header
hello inhere
footer

Index

Examples

Constants

View Source
const DefaultExt = ".tpl"

DefaultExt name

View Source
const DefaultExt1 = ".tmpl"

Variables

This section is empty.

Functions

func AddFunc added in v1.1.0

func AddFunc(name string, fn any)

AddFunc add template func

func AddFuncMap added in v1.1.0

func AddFuncMap(fm template.FuncMap)

AddFuncMap add template func map

func DisableLayout added in v1.1.0

func DisableLayout(r *Renderer)

DisableLayout disable the layout template.

func EnableExtends added in v1.1.0

func EnableExtends(r *Renderer)

EnableExtends enable extends feature.

func Execute added in v1.1.0

func Execute(w io.Writer, tplName string, v any) error

Execute render partial, will not render layout file

func Initialize added in v1.1.0

func Initialize(fns ...OptionFn)

Initialize the default instance with config func

func LoadByGlob added in v1.1.0

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

LoadByGlob load templates by glob pattern.

func LoadFiles added in v1.1.0

func LoadFiles(files ...string)

LoadFiles load custom template files.

func LoadString added in v1.1.0

func LoadString(tplName string, tplString string)

LoadString load named template string.

func LoadStrings added in v1.1.0

func LoadStrings(sMap map[string]string)

LoadStrings load multi named template strings

func Partial added in v1.1.0

func Partial(w io.Writer, tplName string, v any) error

Partial is alias of the Execute()

func Render added in v1.1.0

func Render(w io.Writer, tplName string, v any, layout ...string) error

Render a template name/file with layout, write result to the Writer.

func Reset added in v1.1.0

func Reset()

Reset the default instance

func Revert added in v1.1.0

func Revert()

Revert the default instance, alias of Reset()

func String added in v1.1.0

func String(w io.Writer, tplStr string, v any) error

String render a template string

func WithDebug added in v1.1.0

func WithDebug(r *Renderer)

WithDebug set enable debug mode.

Types

type M

type M map[string]any

M a short type for map[string]any

type OptionFn added in v1.1.0

type OptionFn func(r *Renderer)

OptionFn for renderer

func WithLayout added in v1.1.0

func WithLayout(layoutName string) OptionFn

WithLayout set the layout template name.

func WithTplDirs added in v1.1.0

func WithTplDirs(dirs string) OptionFn

WithTplDirs set template dirs

func WithViewDirs added in v1.1.0

func WithViewDirs(dirs string) OptionFn

WithViewDirs set template dirs, alias of WithTplDirs()

type Options added in v1.1.0

type Options struct {
	// Debug mode for development.
	Debug bool
	// Delims define for template. default is "{{", "}}"
	Delims TplDelims
	// ViewsDir the default views directory, multi dirs use "," split
	ViewsDir string
	// ExtNames supported template extensions, without dot prefix. eg {"tpl", "html"}
	ExtNames []string
	// FuncMap func map for template
	FuncMap template.FuncMap

	// Layout template name for default.
	Layout string
	// DisableLayout disable apply layout render. default is False
	DisableLayout bool

	// EnableExtends enable extends feature. default is False
	EnableExtends bool
	// ExtendsBase template file map. available when extends feature is enabled.
	// 	- Key is tpl name, value is base tpl file path.
	//
	// Example:
	// 	{"base": "/path/to/base.tpl"}
	// Use on template page.tpl:
	// 	{{ extends "base" }}
	// 	{{ define "body" }} ... {{ end }}
	ExtendsBase map[string]string
	// AutoSearchFile
	// TODO: auto search template file, when not found on compiled templates. default is False
	AutoSearchFile bool
}

Options for renderer

type Renderer

type Renderer struct {
	Options
	// contains filtered or unexported fields
}

Renderer definition

func Default added in v1.1.0

func Default() *Renderer

Default get default instance

func New added in v1.1.0

func New(fns ...OptionFn) *Renderer

New create a new template renderer, but not initialized.

func NewExtends added in v1.1.0

func NewExtends(fns ...OptionFn) *Renderer

NewExtends create a new and initialized template renderer. default enable extends feature.

func NewInited added in v1.1.0

func NewInited(fns ...OptionFn) *Renderer

NewInited create a new and initialized template renderer. alias of NewInitialized()

func NewInitialized

func NewInitialized(fns ...OptionFn) *Renderer

NewInitialized create a new and initialized view renderer.

func NewRenderer

func NewRenderer(fns ...OptionFn) *Renderer

NewRenderer create a new view renderer

func (*Renderer) AddFunc

func (r *Renderer) AddFunc(name string, fn any)

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.1.0

func (r *Renderer) Execute(w io.Writer, tplName string, v any) (err error)

Execute render partial, will not render layout file

func (*Renderer) Init added in v1.1.0

func (r *Renderer) Init() error

Init Initialize templates in the viewsDir, add do some prepare works.

Notice: must call it on after create Renderer

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. will panic on error

Usage:

r.LoadByGlob("views/*")
r.LoadByGlob("views/*", "views") // register template will remove prefix "views"
r.LoadByGlob("views/*.tpl") // add ext limit
r.LoadByGlob("views/**/*") // all sub-dir files

func (*Renderer) LoadBytes added in v1.1.0

func (r *Renderer) LoadBytes(tplName string, tplText []byte)

LoadBytes load named template bytes. will panic on error

func (*Renderer) LoadFile added in v1.1.0

func (r *Renderer) LoadFile(tplName, filePath string)

LoadFile load named template file. will panic on error

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, tplText string)

LoadString load named template string. will panic on error

Usage:

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

func (*Renderer) LoadStrings

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

LoadStrings load multi named template strings. key is template name, value is template contents.

func (*Renderer) MustInit added in v1.1.0

func (r *Renderer) MustInit() *Renderer

MustInit compile templates, will panic on error

func (*Renderer) MustInitialize deprecated

func (r *Renderer) MustInitialize()

MustInitialize compile templates and report error

Deprecated: please use MustInit, will remove this method in the future

func (*Renderer) Partial

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

Partial is alias of the Execute()

func (*Renderer) Render

func (r *Renderer) Render(w io.Writer, tplName string, v any, layout ...string) error

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

Usage:

renderer := easytpl.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) Root added in v1.1.0

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

Root returns root template instance

func (*Renderer) String

func (r *Renderer) String(w io.Writer, tplText string, v any) error

String render a template string with data

func (*Renderer) Template

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

Template get template instance by name, if not exists, return nil

func (*Renderer) TemplateFiles

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

TemplateFiles returns loaded template files

func (*Renderer) TemplateNames

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

TemplateNames returns loaded template names.

return string like: "tpl1, tpl2, tpl3"

func (*Renderer) Templates

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

Templates returns loaded template instances, including ROOT itself.

func (*Renderer) WithOptions added in v1.1.0

func (r *Renderer) WithOptions(fns ...OptionFn) *Renderer

WithOptions apply config functions

type TplDelims

type TplDelims struct {
	Left  string
	Right string
}

TplDelims for html template

Directories

Path Synopsis
Package tplfunc provides a default FuncMap for use with text/template and html/template.
Package tplfunc provides a default FuncMap for use with text/template and html/template.

Jump to

Keyboard shortcuts

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