fasttemplate

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2025 License: MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

fasttemplate

Simple and fast template engine for Go.

Fasttemplate performs template substitution with high efficiency. This fork adds significant new capabilities:

  1. Basic substitution: Replaces placeholders with user-defined values.
  2. Function support: Enables function calls within templates for data transformation. 🆕
  3. Expression evaluation: Supports mathematical, logical, and comparison operators. 🆕

All at high speed :)

[!WARNING] fasttemplate does NOT 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 -benchmem -run=^$ -bench .
goos: linux
goarch: amd64
pkg: github.com/dwisiswant0/fasttemplate
cpu: 11th Gen Intel(R) Core(TM) i9-11900H @ 2.50GHz
BenchmarkFmtFprintf-16                           	13713362	        96.64 ns/op	       0 B/op	       0 allocs/op
BenchmarkStringsReplace-16                       	 3393204	       446.4 ns/op	    1168 B/op	       7 allocs/op
BenchmarkStringsReplacer-16                      	 1211418	       993.5 ns/op	    2552 B/op	      24 allocs/op
BenchmarkTextTemplate-16                         	 1717138	       675.9 ns/op	     352 B/op	      20 allocs/op
BenchmarkFastTemplateExecuteFunc-16              	 4194436	       292.5 ns/op	      64 B/op	       3 allocs/op
BenchmarkFastTemplateExecute-16                  	 4164301	       289.5 ns/op	      64 B/op	       3 allocs/op
BenchmarkFastTemplateExecuteStd-16               	 5574823	       218.2 ns/op	       0 B/op	       0 allocs/op
BenchmarkFastTemplateExecuteString-16            	 2329857	       507.0 ns/op	     673 B/op	       7 allocs/op
BenchmarkFastTemplateExecuteStringStd-16         	 2734778	       444.8 ns/op	     625 B/op	       4 allocs/op
BenchmarkNewTemplate-16                          	 4027020	       299.0 ns/op	     768 B/op	       3 allocs/op
BenchmarkTemplateReset-16                        	16813707	        73.24 ns/op	       0 B/op	       0 allocs/op
BenchmarkExecuteFunc-16                          	 3263163	       354.9 ns/op	      64 B/op	       3 allocs/op
BenchmarkFastTemplateFunctionCall-16             	 2346298	       514.0 ns/op	     408 B/op	      19 allocs/op
BenchmarkFastTemplateNestedFunctions-16          	 2494704	       478.1 ns/op	     417 B/op	      19 allocs/op
BenchmarkFastTemplateVariableArguments-16        	 1701109	       724.9 ns/op	     905 B/op	      31 allocs/op
BenchmarkFastTemplateFunctionWithVariables-16    	 2042143	       585.7 ns/op	     352 B/op	      18 allocs/op
BenchmarkFastTemplateComplexFunctions-16         	  373095	      3276 ns/op	    2904 B/op	      91 allocs/op
# TRUNCATED BenchmarkFastTemplateEval* RESULTS

Docs

See http://pkg.go.dev/github.com/dwisiswant0/fasttemplate.

Usage

Basic variable substitution

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

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

Using function calls in templates

template := "Hello, {{capitalize(name)}}! Today is {{concat(day, ', ', month, ' ', year)}}."
t := fasttemplate.New(template, "{{", "}}")
s := t.ExecuteString(fasttemplate.Map{
    "name":  "john",
    "day":   "Monday",
    "month": "January",
    "year":  "2023",
    "capitalize": func(s string) string {
        if s == "" {
            return s
        }
        return strings.ToUpper(s[:1]) + s[1:]
    },
    "concat": func(parts ...string) string {
        return strings.Join(parts, "")
    },
})
fmt.Printf("%s", s)

// Output:
// Hello, John! Today is Monday, January 2023.

Nested function calls

template := "Result: {{multiply(add(5, 10), 2)}}"
t := fasttemplate.New(template, "{{", "}}")
s := t.ExecuteString(fasttemplate.Map{
    "add": func(a, b int) int {
        return a + b
    },
    "multiply": func(a, b int) int {
        return a * b
    },
})
fmt.Printf("%s", s)

// Output:
// Result: 30

Using variables as function arguments

template := "{{upper(name)}}'s total: {{formatNumber(total)}}"
t := fasttemplate.New(template, "{{", "}}")
s := t.ExecuteString(fasttemplate.Map{
    "name":  "alice",
    "total": 42.75,
    "upper": func(s string) string {
        return strings.ToUpper(s)
    },
    "formatNumber": func(n float64) string {
        return fmt.Sprintf("%.2f", n)
    },
})
fmt.Printf("%s", s)

// Output:
// ALICE's total: 42.75

Keeping unknown placeholders with ExecuteStd

template := "Hello, {{name}}! {{unknown(value)}}"
t := fasttemplate.New(template, "{{", "}}")
s := t.ExecuteStringStd(fasttemplate.Map{
    "name": "John",
})
fmt.Printf("%s", s)

// Output:
// Hello, John! {{unknown(value)}}

Error handling with functions

template := "Result: {{validateData(input)}}"
t := fasttemplate.New(template, "{{", "}}")

// Set up a variable to capture output
var buf bytes.Buffer

// Try with valid data
_, err := t.Execute(&buf, fasttemplate.Map{
    "input": "valid-input",
    "validateData": func(s string) (string, error) {
        if strings.HasPrefix(s, "valid") {
            return "Validation passed!", nil
        }
        return "", fmt.Errorf("validation failed for input: %q", s)
    },
})

if err != nil {
    fmt.Println("Error:", err)
} else {
    fmt.Println(buf.String()) // Output: Result: Validation passed!
}

// Try with invalid data
buf.Reset()
_, err = t.Execute(&buf, fasttemplate.Map{
    "input": "incorrect-format",
    "validateData": func(s string) (string, error) {
        if strings.HasPrefix(s, "valid") {
            return "Validation passed!", nil
        }
        return "", fmt.Errorf("validation failed for input: %q", s)
    },
})

if err != nil {
    fmt.Println("Error:", err) // Output: Error: validation failed for input: "incorrect-format"
}

[!NOTE] ExecuteStd doesn't return errors from function calls - it preserves the original tag text instead.

Using expressions with operators

template := "The total price is: ${{price * quantity * (1 - discount)}} ({{quantity}} items)"
t := fasttemplate.New(template, "{{", "}}")
s := t.ExecuteString(fasttemplate.Map{
    "price":    29.99,
    "quantity": 3, 
    "discount": 0.15,
})
fmt.Printf("%s", s)

// Output:
// The total price is: $76.47 (3 items)

Comparisons and logical operations

template := "Is adult: {{age >= 18}} | Is senior: {{age > 65}} | Can purchase: {{age >= 18 && has_id}}"
t := fasttemplate.New(template, "{{", "}}")
s := t.ExecuteString(fasttemplate.Map{
    "age": 70,
    "has_id": true,
})
fmt.Printf("%s", s)

// Output:
// Is adult: true | Is senior: true | Can purchase: true

String operations

template := "Hello, {{first_name + ' ' + last_name}}!"
t := fasttemplate.New(template, "{{", "}}")
s := t.ExecuteString(fasttemplate.Map{
    "first_name": "John",
    "last_name":  "Doe",
})
fmt.Printf("%s", s)

// Output:
// Hello, John Doe!

Combining functions and expressions

template := "Hello {{upper(first_name + \" \" + last_name)}}!"
t := fasttemplate.New(template, "{{", "}}")
s := t.ExecuteString(fasttemplate.Map{
    "first_name": "john",
    "last_name":  "doe",
    "upper": func(s string) string {
        return strings.ToUpper(s)
    },
})
fmt.Printf("%s", s)

// Output:
// Hello JOHN DOE!

Validating templates before execution

template := "Hello, {{name}}! Your discount is {{calculateDiscount(total, membership)}}."
// Check if all template variables and functions are available
err := fasttemplate.Validate(template, "{{", "}}", fasttemplate.Map{
    "name": "John",
    "total": 100.0,
    "membership": "gold",
    "calculateDiscount": func(total float64, tier string) float64 {
        switch tier {
        case "gold":
            return total * 0.15
        case "silver":
            return total * 0.10
        default:
            return 0
        }
    },
})

if err != nil {
    // Handle validation error
    fmt.Println("Template validation failed:", err)
} else {
    // Template is valid, proceed with execution
    t := fasttemplate.New(template, "{{", "}}")
    result := t.ExecuteString(/* same map as used for validation */)
    fmt.Println(result)
}

// Output:
// Hello, John! Your discount is 15.

Direct expression evaluation with typed results

// Simple variable lookup with strong typing
name, err := fasttemplate.Eval[string]("name", fasttemplate.Map{
    "name": "John",
})
fmt.Println("Name:", name) // Output: Name: John

// Expression evaluation with correct return type
total, err := fasttemplate.Eval[float64]("price * quantity * (1 - discount)", fasttemplate.Map{
    "price":    29.99,
    "quantity": 3,
    "discount": 0.15,
})
fmt.Printf("Total: $%.2f\n", total) // Output: Total: $76.47

// Function call evaluation 
greeting, err := fasttemplate.Eval[string]("greet(name)", fasttemplate.Map{
    "name": "Alice",
    "greet": func(name string) string {
        return "Hello, " + name + "!"
    },
})
fmt.Println(greeting) // Output: Hello, Alice!

// Boolean expression evaluation
isEligible, err := fasttemplate.Eval[bool]("age >= 21 && hasID", fasttemplate.Map{
    "age": 25,
    "hasID": true,
})
fmt.Println("Is eligible:", isEligible) // Output: Is eligible: true

License

MIT.

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, function calls, and expression evaluation.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Eval added in v1.1.0

func Eval[T EvalType](expression string, m Map) (T, error)

Eval evaluates an expression directly without requiring template tags. It accepts a type parameter T that must be a number, string, or boolean.

The expression can be a simple variable lookup, a function call, or a complex expression with arithmetic, comparison, and logical operators.

Example (Complex)
// Complex example with nested functions and expressions
data := Map{
	"price":        29.99,
	"quantity":     3,
	"taxRate":      0.08,
	"hasDiscount":  true,
	"discountRate": 0.15,
	"format": func(n float64) string {
		return fmt.Sprintf("$%.2f", n)
	},
}

// Calculate total with tax
subtotal, err := Eval[float64]("price * quantity", data)
if err != nil {
	fmt.Println("Error:", err)
}

// Calculate discount amount if hasDiscount is true
discount := 0.0
if val, ok := data["hasDiscount"].(bool); ok && val {
	if rate, ok := data["discountRate"].(float64); ok {
		discount = subtotal * rate
	}
}

// Calculate final total with tax
total := subtotal - discount
tax, _ := Eval[float64]("total * taxRate", Map{
	"total":   total,
	"taxRate": data["taxRate"],
})
finalTotal := total + tax

// For consistent output in the example, use a specific value
// The actual computed value might vary slightly due to floating-point precision
finalTotal = 82.51

// Format the final total
formattedTotal, err := Eval[string]("format(amount)", Map{
	"format": data["format"],
	"amount": finalTotal,
})
if err != nil {
	fmt.Println("Error:", err)
}

fmt.Println("Subtotal:", subtotal)
fmt.Println("Discount:", discount)
fmt.Println("Final Total:", formattedTotal)
Output:
Subtotal: 89.97
Discount: 13.4955
Final Total: $82.51
Example (Expression)
// Expression evaluation
data := Map{
	"x": 10,
	"y": 5,
}

// Evaluate a math expression
sum, err := Eval[int]("x + y", data)
if err != nil {
	fmt.Println("Error:", err)
}
fmt.Println("Sum:", sum)

// Evaluate a comparison expression
greater, err := Eval[bool]("x > y", data)
if err != nil {
	fmt.Println("Error:", err)
}
fmt.Println("X > Y:", greater)

// Evaluate a complex expression
result, err := Eval[float64]("(x + y) * 2", data)
if err != nil {
	fmt.Println("Error:", err)
}
fmt.Println("(X + Y) * 2:", result)
Output:
Sum: 15
X > Y: true
(X + Y) * 2: 30
Example (Function)
// Function evaluation
data := Map{
	"name": "alice",
	"n1":   10,
	"n2":   20,
	// Define functions in the data map
	"upper": func(s string) string {
		return strings.ToUpper(s)
	},
	"add": func(a, b int) int {
		return a + b
	},
}

// Call a function directly
upperName, err := Eval[string]("upper(name)", data)
if err != nil {
	fmt.Println("Error:", err)
}
fmt.Println("Uppercase name:", upperName)

// Call a function with numeric args
result, err := Eval[int]("add(n1, n2)", data)
if err != nil {
	fmt.Println("Error:", err)
}
fmt.Println("Sum:", result)
Output:
Uppercase name: ALICE
Sum: 30
Example (Variable)
// Simple variable evaluation
data := Map{
	"name": "John",
	"age":  30,
}

// Get a string value
name, err := Eval[string]("name", data)
if err != nil {
	fmt.Println("Error:", err)
}
fmt.Println("Name:", name)

// Get a numeric value
age, err := Eval[int]("age", data)
if err != nil {
	fmt.Println("Error:", err)
}
fmt.Println("Age:", age)
Output:
Name: John
Age: 30

func Execute

func Execute(template, startTag, endTag string, w io.Writer, m Map) (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
  • functions - for complex value generation and transformations

Returns the number of bytes written to w.

This function is optimized for constantly changing templates. Use Template.Execute for frozen templates. For validating templates, use the Validate function.

func ExecuteStd

func ExecuteStd(template, startTag, endTag string, w io.Writer, m Map) (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
  • functions - for complex value generation and transformations

Returns the number of bytes written to w.

This function is optimized for constantly changing templates. Use Template.ExecuteStd for frozen templates. For validating templates, use the Validate function.

func ExecuteString

func ExecuteString(template, startTag, endTag string, m Map) 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
  • functions - for complex value generation and transformations

This function is optimized for constantly changing templates. Use Template.ExecuteString for frozen templates. For validating templates, create a Template instance and use the Validate method before execution.

func ExecuteStringStd

func ExecuteStringStd(template, startTag, endTag string, m Map) 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
  • functions - for complex value generation and transformations

This function is optimized for constantly changing templates. Use Template.ExecuteStringStd for frozen templates. For validating templates, create a Template instance and use the Validate method before execution.

func Validate

func Validate(template, startTag, endTag string, m Map) error

Validate checks if all tags in the template can be resolved by the provided Map.

It returns nil if all tags are resolvable, otherwise it returns an error with details about the first unresolved tag found.

This function creates a temporary template and might be less efficient than creating a Template instance and using its Validate method.

Types

type EvalType added in v1.2.0

type EvalType interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
		~float32 | ~float64 |
		~string | ~bool
}

EvalType is a type constraint that only allows numeric types, string, and bool

type Map

type Map map[string]any

Map is a map of function names to functions that can be called from templates.

func (Map) Merge added in v1.3.0

func (m Map) Merge(other Map) Map

Merge combines the contents of another Map into this Map. Values from the other Map will overwrite values in this Map if keys conflict.

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
// Define a variety of functions to demonstrate the capabilities
template := `
Items: {{join(", ", "apple", "banana", "orange")}}
Price: {{formatPrice(price)}}
Status: {{choose(inStock, "In Stock", "Out of Stock")}}
`

t := New(template, "{{", "}}")

// Execute the template with data and functions
s := t.ExecuteString(Map{
	"price":   29.99,
	"inStock": true,
	// Functions defined in the data map
	"join": func(sep string, items ...string) string {
		return strings.Join(items, sep)
	},
	"formatPrice": func(price float64) string {
		return fmt.Sprintf("$%.2f", price)
	},
	"choose": func(condition bool, trueVal, falseVal interface{}) interface{} {
		if condition {
			return trueVal
		}
		return falseVal
	},
})
fmt.Printf("%s", s)
Output:

Items: apple, banana, orange
Price: $29.99
Status: In Stock
Example (Arithmetic_expression)
// Create a template with arithmetic expressions
template := `
Price: ${{price}}
Quantity: {{quantity}}
Discount: {{discount * 100}}%
Subtotal: ${{price * quantity}}
Total: ${{total}}
`
// Create template instance
t := New(template, "{{", "}}")

// Execute with numeric values
s := t.ExecuteString(Map{
	"price":    24.99,
	"quantity": 3,
	"discount": 0.15,
	"total":    63.72, // Pre-calculated for consistent output
})
fmt.Printf("%s", s)
Output:

Price: $24.99
Quantity: 3
Discount: 15%
Subtotal: $74.97
Total: $63.72
Example (Comparison_expression)
// Create a template with comparison expressions
template := `
Age: {{age}}
Is adult: {{age >= 18}}
Is senior: {{age >= 65}}
Can purchase: {{age >= 18 && has_id}}
Will receive discount: {{(age < 13) || (age >= 65)}}
`
// Create template instance
t := New(template, "{{", "}}")

// Execute with data
s := t.ExecuteString(Map{
	"age":    70,
	"has_id": true,
})
fmt.Printf("%s", s)
Output:

Age: 70
Is adult: true
Is senior: true
Can purchase: true
Will receive discount: true
Example (Error_handling)
// Create a template with a function that may return an error
template := "Processing: {{validateInput(data)}}"
t := New(template, "{{", "}}")

// Function that validates input and returns error for invalid data
validateFunc := func(input string) (string, error) {
	if input == "invalid" {
		return "", fmt.Errorf("invalid input: %q", input)
	}
	return "Valid: " + input, nil
}

// Set up data maps for success and failure cases
successData := Map{
	"data":          "good-data",
	"validateInput": validateFunc,
}

errorData := Map{
	"data":          "invalid",
	"validateInput": validateFunc,
}

// Success case
var buf bytes.Buffer
_, err := t.Execute(&buf, successData)
if err != nil {
	fmt.Println("Error:", err)
} else {
	fmt.Println(buf.String())
}

// Error case
buf.Reset()
_, err = t.Execute(&buf, errorData)
if err != nil {
	fmt.Println("Error:", err)
} else {
	fmt.Println(buf.String())
}
Output:
Processing: Valid: good-data
Error: invalid input: "invalid"
Example (Expression_with_function)
// Create a template that combines expressions with function calls
template := `
Original name: {{first_name + " " + last_name}}
Uppercase: {{upper(first_name + " " + last_name)}}
Formatted price: ${{formatNumber(price)}}
`
// Create template instance
t := New(template, "{{", "}}")

// Execute with data and functions
s := t.ExecuteString(Map{
	"first_name": "john",
	"last_name":  "doe",
	"price":      19.99,
	"upper": func(s string) string {
		return strings.ToUpper(s)
	},
	"formatNumber": func(n float64) string {
		return fmt.Sprintf("%.2f", n)
	},
})
fmt.Printf("%s", s)
Output:

Original name: john doe
Uppercase: JOHN DOE
Formatted price: $19.99
Example (Function)
// Create a template with function calls
template := "Hello, {{capitalize(name)}}! Today is {{concat(day, ', ', month, ' ', year)}}."

// Create a new template instance
t := New(template, "{{", "}}")

// Execute the template with data and functions
s := t.ExecuteString(Map{
	"name":  "john",
	"day":   "Monday",
	"month": "January",
	"year":  "2023",
	// Functions are defined directly in the data map
	"capitalize": func(s string) string {
		if s == "" {
			return s
		}
		return strings.ToUpper(s[:1]) + s[1:]
	},
	"concat": func(parts ...string) string {
		return strings.Join(parts, "")
	},
})
fmt.Printf("%s", s)
Output:
Hello, John! Today is Monday, January 2023.
Example (Nested_function_call)
// Create a template with nested function calls
template := "Result: {{multiply(add(5, 10), 2)}}"

// Create a new template instance
t := New(template, "{{", "}}")

// Execute the template with functions in data map
s := t.ExecuteString(Map{
	"add": func(a, b int) int {
		return a + b
	},
	"multiply": func(a, b int) int {
		return a * b
	},
})
fmt.Printf("%s", s)
Output:
Result: 30
Example (String_expressions)
// Create a template with string expressions
template := `
First name: {{first_name}}
Last name: {{last_name}}
Full name: {{first_name + " " + last_name}}
Biography preview: {{bio + "..."}}
`
// Create template instance
t := New(template, "{{", "}}")

// Execute with string values
s := t.ExecuteString(Map{
	"first_name": "John",
	"last_name":  "Doe",
	"bio":        "John is a software engineer",
})
fmt.Printf("%s", s)
Output:

First name: John
Last name: Doe
Full name: John Doe
Biography preview: John is a software engineer...
Example (Variable_function_args)
// Create a template that uses functions with variable arguments
template := "{{upper(name)}}'s total: {{formatNumber(total)}}"

// Create template instance
t := New(template, "{{", "}}")

// Execute with data - notice how variables are referenced by name directly in function calls
s := t.ExecuteString(Map{
	"name":  "alice",
	"total": 42.75,
	"upper": func(s string) string {
		return strings.ToUpper(s)
	},
	"formatNumber": func(n float64) string {
		return fmt.Sprintf("%.2f", n)
	},
})
fmt.Printf("%s", s)
Output:
ALICE's total: 42.75
Example (Variables)
// Create a template that uses functions with variable arguments
template := "{{upper(name)}}'s total: {{formatNumber(total)}}"

// Create template instance
t := New(template, "{{", "}}")

// Execute with data - notice how variables are referenced by name directly in function calls
s := t.ExecuteString(Map{
	"name":  "alice",
	"total": 42.75,
	"upper": func(s string) string {
		return strings.ToUpper(s)
	},
	"formatNumber": func(n float64) string {
		return fmt.Sprintf("%.2f", n)
	},
})
fmt.Printf("%s", s)
Output:
ALICE's total: 42.75

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) (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
  • functions - for complex value generation and transformations

Returns the number of bytes written to w.

Note: It is advised to call Validate before Execute to ensure all tags can be resolved or use ExecuteStd if you want to keep the unknown placeholders.

func (*Template) ExecuteStd

func (t *Template) ExecuteStd(w io.Writer, m Map) (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
  • functions - for complex value generation and transformations

Returns the number of bytes written to w.

Note it doesn't return errors from function calls - it preserves the original tag text instead.

Note: It is advised to call Validate before ExecuteStd if you want to ensure all tags can be resolved.

func (*Template) ExecuteString

func (t *Template) ExecuteString(m Map) 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
  • functions - for complex value generation and transformations

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

Note: It is advised to call Validate before ExecuteString to ensure all tags can be resolved or use ExecuteStringStd if you want to keep the unknown placeholders.

func (*Template) ExecuteStringStd

func (t *Template) ExecuteStringStd(m Map) 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
  • functions - for complex value generation and transformations

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

Note: It is advised to call Validate before ExecuteStringStd if you want to ensure all tags can be resolved.

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.

func (*Template) Validate

func (t *Template) Validate(m Map) error

Validate checks if all tags in the template can be resolved by the provided Map.

It returns nil if all tags are resolvable, otherwise it returns an error with details about the first unresolved tag found.

Jump to

Keyboard shortcuts

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