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 ¶
- func Eval[T EvalType](expression string, m Map) (T, error)
- func Execute(template, startTag, endTag string, w io.Writer, m Map) (int64, error)
- func ExecuteStd(template, startTag, endTag string, w io.Writer, m Map) (int64, error)
- func ExecuteString(template, startTag, endTag string, m Map) string
- func ExecuteStringStd(template, startTag, endTag string, m Map) string
- func Validate(template, startTag, endTag string, m Map) error
- type EvalType
- type Map
- type Template
- func (t *Template) Execute(w io.Writer, m Map) (int64, error)
- func (t *Template) ExecuteStd(w io.Writer, m Map) (int64, error)
- func (t *Template) ExecuteString(m Map) string
- func (t *Template) ExecuteStringStd(m Map) string
- func (t *Template) Reset(template, startTag, endTag string) error
- func (t *Template) Validate(m Map) error
Examples ¶
- Eval (Complex)
- Eval (Expression)
- Eval (Function)
- Eval (Variable)
- Template
- Template (Arithmetic_expression)
- Template (Comparison_expression)
- Template (Error_handling)
- Template (Expression_with_function)
- Template (Function)
- Template (Nested_function_call)
- Template (String_expressions)
- Template (Variable_function_args)
- Template (Variables)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Eval ¶ added in v1.1.0
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.