fasttemplate

package module
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2022 License: MIT Imports: 6 Imported by: 840

README

fasttemplate

Simple and fast template engine for Go.

Fasttemplate performs only a single task - it substitutes template placeholders with user-defined values. At high speed :)

Take a look at quicktemplate if you need fast yet powerful html template engine.

Please note that fasttemplate doesn't do any escaping on template values unlike html/template do. So values must be properly escaped before passing them to fasttemplate.

Fasttemplate is faster than text/template, strings.Replace, strings.Replacer and fmt.Fprintf on placeholders' substitution.

Below are benchmark results comparing fasttemplate performance to text/template, strings.Replace, strings.Replacer and fmt.Fprintf:

$ go test -bench=. -benchmem
PASS
BenchmarkFmtFprintf-4                   	 2000000	       790 ns/op	       0 B/op	       0 allocs/op
BenchmarkStringsReplace-4               	  500000	      3474 ns/op	    2112 B/op	      14 allocs/op
BenchmarkStringsReplacer-4              	  500000	      2657 ns/op	    2256 B/op	      23 allocs/op
BenchmarkTextTemplate-4                 	  500000	      3333 ns/op	     336 B/op	      19 allocs/op
BenchmarkFastTemplateExecuteFunc-4      	 5000000	       349 ns/op	       0 B/op	       0 allocs/op
BenchmarkFastTemplateExecute-4          	 3000000	       383 ns/op	       0 B/op	       0 allocs/op
BenchmarkFastTemplateExecuteFuncString-4	 3000000	       549 ns/op	     144 B/op	       1 allocs/op
BenchmarkFastTemplateExecuteString-4    	 3000000	       572 ns/op	     144 B/op	       1 allocs/op
BenchmarkFastTemplateExecuteTagFunc-4   	 2000000	       743 ns/op	     144 B/op	       3 allocs/op

Docs

See http://godoc.org/github.com/valyala/fasttemplate .

Usage

	template := "http://{{host}}/?q={{query}}&foo={{bar}}{{bar}}"
	t := fasttemplate.New(template, "{{", "}}")
	s := t.ExecuteString(map[string]interface{}{
		"host":  "google.com",
		"query": url.QueryEscape("hello=world"),
		"bar":   "foobar",
	})
	fmt.Printf("%s", s)

	// Output:
	// http://google.com/?q=hello%3Dworld&foo=foobarfoobar

Advanced usage

	template := "Hello, [user]! You won [prize]!!! [foobar]"
	t, err := fasttemplate.NewTemplate(template, "[", "]")
	if err != nil {
		log.Fatalf("unexpected error when parsing template: %s", err)
	}
	s := t.ExecuteFuncString(func(w io.Writer, tag string) (int, error) {
		switch tag {
		case "user":
			return w.Write([]byte("John"))
		case "prize":
			return w.Write([]byte("$100500"))
		default:
			return w.Write([]byte(fmt.Sprintf("[unknown tag %q]", tag)))
		}
	})
	fmt.Printf("%s", s)

	// Output:
	// Hello, John! You won $100500!!! [unknown tag "foobar"]

Documentation

Overview

Package fasttemplate implements simple and fast template library.

Fasttemplate is faster than text/template, strings.Replace and strings.Replacer.

Fasttemplate ideally fits for fast and simple placeholders' substitutions.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Execute

func Execute(template, startTag, endTag string, w io.Writer, m map[string]interface{}) (int64, error)

Execute substitutes template tags (placeholders) with the corresponding values from the map m and writes the result to the given writer w.

Substitution map m may contain values with the following types:

  • []byte - the fastest value type
  • string - convenient value type
  • TagFunc - flexible value type

Returns the number of bytes written to w.

This function is optimized for constantly changing templates. Use Template.Execute for frozen templates.

func ExecuteFunc

func ExecuteFunc(template, startTag, endTag string, w io.Writer, f TagFunc) (int64, error)

ExecuteFunc calls f on each template tag (placeholder) occurrence.

Returns the number of bytes written to w.

This function is optimized for constantly changing templates. Use Template.ExecuteFunc for frozen templates.

func ExecuteFuncString

func ExecuteFuncString(template, startTag, endTag string, f TagFunc) string

ExecuteFuncString calls f on each template tag (placeholder) occurrence and substitutes it with the data written to TagFunc's w.

Returns the resulting string.

This function is optimized for constantly changing templates. Use Template.ExecuteFuncString for frozen templates.

func ExecuteFuncStringWithErr added in v1.1.1

func ExecuteFuncStringWithErr(template, startTag, endTag string, f TagFunc) (string, error)

ExecuteFuncStringWithErr is nearly the same as ExecuteFuncString but when f returns an error, ExecuteFuncStringWithErr won't panic like ExecuteFuncString it just returns an empty string and the error f returned

func ExecuteStd added in v1.2.0

func ExecuteStd(template, startTag, endTag string, w io.Writer, m map[string]interface{}) (int64, error)

ExecuteStd works the same way as Execute, but keeps the unknown placeholders. This can be used as a drop-in replacement for strings.Replacer

Substitution map m may contain values with the following types:

  • []byte - the fastest value type
  • string - convenient value type
  • TagFunc - flexible value type

Returns the number of bytes written to w.

This function is optimized for constantly changing templates. Use Template.ExecuteStd for frozen templates.

func ExecuteString

func ExecuteString(template, startTag, endTag string, m map[string]interface{}) string

ExecuteString substitutes template tags (placeholders) with the corresponding values from the map m and returns the result.

Substitution map m may contain values with the following types:

  • []byte - the fastest value type
  • string - convenient value type
  • TagFunc - flexible value type

This function is optimized for constantly changing templates. Use Template.ExecuteString for frozen templates.

func ExecuteStringStd added in v1.2.0

func ExecuteStringStd(template, startTag, endTag string, m map[string]interface{}) string

ExecuteStringStd works the same way as ExecuteString, but keeps the unknown placeholders. This can be used as a drop-in replacement for strings.Replacer

Substitution map m may contain values with the following types:

  • []byte - the fastest value type
  • string - convenient value type
  • TagFunc - flexible value type

This function is optimized for constantly changing templates. Use Template.ExecuteStringStd for frozen templates.

Types

type TagFunc

type TagFunc func(w io.Writer, tag string) (int, error)

TagFunc can be used as a substitution value in the map passed to Execute*. Execute* functions pass tag (placeholder) name in 'tag' argument.

TagFunc must be safe to call from concurrently running goroutines.

TagFunc must write contents to w and return the number of bytes written.

Example
template := "foo[baz]bar"
t, err := NewTemplate(template, "[", "]")
if err != nil {
	log.Fatalf("unexpected error when parsing template: %s", err)
}

bazSlice := [][]byte{[]byte("123"), []byte("456"), []byte("789")}
m := map[string]interface{}{
	// Always wrap the function into TagFunc.
	//
	// "baz" tag function writes bazSlice contents into w.
	"baz": TagFunc(func(w io.Writer, tag string) (int, error) {
		var nn int
		for _, x := range bazSlice {
			n, err := w.Write(x)
			if err != nil {
				return nn, err
			}
			nn += n
		}
		return nn, nil
	}),
}

s := t.ExecuteString(m)
fmt.Printf("%s", s)
Output:

foo123456789bar

type Template

type Template struct {
	// contains filtered or unexported fields
}

Template implements simple template engine, which can be used for fast tags' (aka placeholders) substitution.

Example
template := "http://{{host}}/?foo={{bar}}{{bar}}&q={{query}}&baz={{baz}}"
t := New(template, "{{", "}}")

// Substitution map.
// Since "baz" tag is missing in the map, it will be substituted
// by an empty string.
m := map[string]interface{}{
	"host": "google.com",     // string - convenient
	"bar":  []byte("foobar"), // byte slice - the fastest

	// TagFunc - flexible value. TagFunc is called only if the given
	// tag exists in the template.
	"query": TagFunc(func(w io.Writer, tag string) (int, error) {
		return w.Write([]byte(url.QueryEscape(tag + "=world")))
	}),
}

s := t.ExecuteString(m)
fmt.Printf("%s", s)
Output:

http://google.com/?foo=foobarfoobar&q=query%3Dworld&baz=

func New

func New(template, startTag, endTag string) *Template

New parses the given template using the given startTag and endTag as tag start and tag end.

The returned template can be executed by concurrently running goroutines using Execute* methods.

New panics if the given template cannot be parsed. Use NewTemplate instead if template may contain errors.

func NewTemplate

func NewTemplate(template, startTag, endTag string) (*Template, error)

NewTemplate parses the given template using the given startTag and endTag as tag start and tag end.

The returned template can be executed by concurrently running goroutines using Execute* methods.

func (*Template) Execute

func (t *Template) Execute(w io.Writer, m map[string]interface{}) (int64, error)

Execute substitutes template tags (placeholders) with the corresponding values from the map m and writes the result to the given writer w.

Substitution map m may contain values with the following types:

  • []byte - the fastest value type
  • string - convenient value type
  • TagFunc - flexible value type

Returns the number of bytes written to w.

func (*Template) ExecuteFunc

func (t *Template) ExecuteFunc(w io.Writer, f TagFunc) (int64, error)

ExecuteFunc calls f on each template tag (placeholder) occurrence.

Returns the number of bytes written to w.

This function is optimized for frozen templates. Use ExecuteFunc for constantly changing templates.

func (*Template) ExecuteFuncString

func (t *Template) ExecuteFuncString(f TagFunc) string

ExecuteFuncString calls f on each template tag (placeholder) occurrence and substitutes it with the data written to TagFunc's w.

Returns the resulting string.

This function is optimized for frozen templates. Use ExecuteFuncString for constantly changing templates.

Example
template := "Hello, [user]! You won [prize]!!! [foobar]"
t, err := NewTemplate(template, "[", "]")
if err != nil {
	log.Fatalf("unexpected error when parsing template: %s", err)
}
s := t.ExecuteFuncString(func(w io.Writer, tag string) (int, error) {
	switch tag {
	case "user":
		return w.Write([]byte("John"))
	case "prize":
		return w.Write([]byte("$100500"))
	default:
		return w.Write([]byte(fmt.Sprintf("[unknown tag %q]", tag)))
	}
})
fmt.Printf("%s", s)
Output:

Hello, John! You won $100500!!! [unknown tag "foobar"]

func (*Template) ExecuteFuncStringWithErr added in v1.1.1

func (t *Template) ExecuteFuncStringWithErr(f TagFunc) (string, error)

ExecuteFuncStringWithErr calls f on each template tag (placeholder) occurrence and substitutes it with the data written to TagFunc's w.

Returns the resulting string.

This function is optimized for frozen templates. Use ExecuteFuncString for constantly changing templates.

func (*Template) ExecuteStd added in v1.2.0

func (t *Template) ExecuteStd(w io.Writer, m map[string]interface{}) (int64, error)

ExecuteStd works the same way as Execute, but keeps the unknown placeholders. This can be used as a drop-in replacement for strings.Replacer

Substitution map m may contain values with the following types:

  • []byte - the fastest value type
  • string - convenient value type
  • TagFunc - flexible value type

Returns the number of bytes written to w.

func (*Template) ExecuteString

func (t *Template) ExecuteString(m map[string]interface{}) string

ExecuteString substitutes template tags (placeholders) with the corresponding values from the map m and returns the result.

Substitution map m may contain values with the following types:

  • []byte - the fastest value type
  • string - convenient value type
  • TagFunc - flexible value type

This function is optimized for frozen templates. Use ExecuteString for constantly changing templates.

func (*Template) ExecuteStringStd added in v1.2.0

func (t *Template) ExecuteStringStd(m map[string]interface{}) string

ExecuteStringStd works the same way as ExecuteString, but keeps the unknown placeholders. This can be used as a drop-in replacement for strings.Replacer

Substitution map m may contain values with the following types:

  • []byte - the fastest value type
  • string - convenient value type
  • TagFunc - flexible value type

This function is optimized for frozen templates. Use ExecuteStringStd for constantly changing templates.

func (*Template) Reset

func (t *Template) Reset(template, startTag, endTag string) error

Reset resets the template t to new one defined by template, startTag and endTag.

Reset allows Template object re-use.

Reset may be called only if no other goroutines call t methods at the moment.

Jump to

Keyboard shortcuts

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