### Custom Delimiters Configuration Source: https://context7.com/valyala/fasttemplate/llms.txt Demonstrates how to initialize templates with non-standard start and end delimiters. ```go package main import ( "fmt" "github.com/valyala/fasttemplate" ) func main() { // Mustache-style triple braces t1 := fasttemplate.New("foo{{{name}}}bar", "{{{", "}}}") fmt.Println(t1.ExecuteString(map[string]interface{}{"name": "test"})) // Output: footestbar // Identical delimiters (like @var@) t2 := fasttemplate.New("Hello @name@, welcome to @place@!", "@", "@") fmt.Println(t2.ExecuteString(map[string]interface{}{"name": "User", "place": "Go"})) // Output: Hello User, welcome to Go! // PHP-style delimiters t3 := fasttemplate.New(" is years old", "") fmt.Println(t3.ExecuteString(map[string]interface{}{"name": "Alice", "age": "30"})) // Output: Alice is 30 years old // Square brackets t4 := fasttemplate.New("Config: [setting]=[value]", "[", "]") fmt.Println(t4.ExecuteString(map[string]interface{}{"setting": "debug", "value": "true"})) // Output: Config: debug=true } ``` -------------------------------- ### Create a Template with New Source: https://context7.com/valyala/fasttemplate/llms.txt Initializes a pre-parsed template using custom delimiters. Note that this function panics if the template is malformed. ```go package main import ( "fmt" "github.com/valyala/fasttemplate" ) func main() { // Create a template with {{ and }} delimiters template := "http://{{host}}/?q={{query}}&foo={{bar}}{{bar}}" t := fasttemplate.New(template, "{{", "}}") // Execute with a substitution map s := t.ExecuteString(map[string]interface{}{ "host": "google.com", "query": "hello%3Dworld", "bar": "foobar", }) fmt.Println(s) // Output: http://google.com/?q=hello%3Dworld&foo=foobarfoobar } ``` -------------------------------- ### Create a Template with NewTemplate Source: https://context7.com/valyala/fasttemplate/llms.txt Safely initializes a template by returning an error instead of panicking on malformed input. ```go package main import ( "fmt" "log" "github.com/valyala/fasttemplate" ) func main() { template := "Hello, [user]! You won [prize]!" t, err := fasttemplate.NewTemplate(template, "[", "]") if err != nil { log.Fatalf("error parsing template: %s", err) } s := t.ExecuteString(map[string]interface{}{ "user": "John", "prize": "$100", }) fmt.Println(s) // Output: Hello, John! You won $100! // Example with malformed template (unclosed tag) _, err = fasttemplate.NewTemplate("Hello [user", "[", "]") if err != nil { fmt.Println("Error:", err) // Output: Error: Cannot find end tag="]" in the template="Hello [user" starting from "user" } } ``` -------------------------------- ### Execute Template to String Source: https://context7.com/valyala/fasttemplate/llms.txt Substitutes placeholders and returns the result as a string. Missing tags are replaced with empty strings. ```go package main import ( "fmt" "github.com/valyala/fasttemplate" ) func main() { t := fasttemplate.New("Name: {name}, Age: {age}, City: {city}", "{", "}") // String values (convenient) result := t.ExecuteString(map[string]interface{}{ "name": "Alice", "age": "30", // "city" is missing - will be replaced with empty string }) fmt.Println(result) // Output: Name: Alice, Age: 30, City: // Byte slice values (fastest) result = t.ExecuteString(map[string]interface{}{ "name": []byte("Bob"), "age": []byte("25"), "city": []byte("NYC"), }) fmt.Println(result) // Output: Name: Bob, Age: 25, City: NYC } ``` -------------------------------- ### Execute Template with Partial Substitution Source: https://context7.com/valyala/fasttemplate/llms.txt Uses ExecuteStringStd to preserve unknown placeholders instead of replacing them with empty strings. ```go package main import ( "fmt" "github.com/valyala/fasttemplate" ) func main() { t := fasttemplate.New("Hello {user}! Your code is {code}. Status: {status}", "{", "}") // Only substitute known values, keep unknown placeholders intact result := t.ExecuteStringStd(map[string]interface{}{ "user": "Alice", // "code" and "status" are not provided }) fmt.Println(result) // Output: Hello Alice! Your code is {code}. Status: {status} } ``` -------------------------------- ### Execute Template to io.Writer Source: https://context7.com/valyala/fasttemplate/llms.txt Writes the substituted template directly to an io.Writer, returning the number of bytes written. ```go package main import ( "bytes" "fmt" "os" "github.com/valyala/fasttemplate" ) func main() { t := fasttemplate.New("User: {{user}}, Role: {{role}}\n", "{{", "}}") // Write to stdout n, err := t.Execute(os.Stdout, map[string]interface{}{ "user": "admin", "role": "superuser", }) // Output: User: admin, Role: superuser fmt.Printf("Wrote %d bytes, error: %v\n", n, err) // Write to a buffer var buf bytes.Buffer t.Execute(&buf, map[string]interface{}{ "user": "guest", "role": "viewer", }) fmt.Println(buf.String()) // Output: User: guest, Role: viewer } ``` -------------------------------- ### Execute for io.Writer Output Source: https://context7.com/valyala/fasttemplate/llms.txt Writes substituted template output directly to an io.Writer, suitable for streaming or buffer-based operations. ```go package main import ( "bytes" "fmt" "github.com/valyala/fasttemplate" ) func main() { var buf bytes.Buffer template := "INSERT INTO users (name, email) VALUES ('{name}', '{email}');\n" users := []map[string]interface{}{ {"name": "Alice", "email": "alice@example.com"}, {"name": "Bob", "email": "bob@example.com"}, } for _, user := range users { fasttemplate.Execute(template, "{", "}", &buf, user) } fmt.Print(buf.String()) // Output: // INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com'); // INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com'); } ``` -------------------------------- ### Execute String Template with Map Values Source: https://github.com/valyala/fasttemplate/blob/master/README.md Use this for simple string template substitution where values can be directly mapped. Ensure values are properly escaped before passing them to ExecuteString. ```go 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) ``` -------------------------------- ### Template.Execute - Substitute placeholders and write to io.Writer Source: https://context7.com/valyala/fasttemplate/llms.txt Substitutes template placeholders and writes the result to an io.Writer. Returns the number of bytes written and any error encountered. ```APIDOC ## Template.Execute Substitutes template placeholders and writes the result to an io.Writer. Returns the number of bytes written and any error encountered. ### Method ```go func (t *Template) Execute(w io.Writer, vars map[string]interface{}) (int64, error) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **w** (io.Writer) - The writer to which the output will be written. - **vars** (map[string]interface{}) - A map where keys are placeholder names and values are the substitution strings or byte slices. ### Request Example ```go package main import ( "bytes" "fmt" "os" "github.com/valyala/fasttemplate" ) func main() { t t := fasttemplate.New("User: {{user}}, Role: {{role}}\n", "{{", "}}") // Write to stdout n, err := t.Execute(os.Stdout, map[string]interface{}{ "user": "admin", "role": "superuser", }) // Output: User: admin, Role: superuser fmt.Printf("Wrote %d bytes, error: %v\n", n, err) // Write to a buffer var buf bytes.Buffer t.Execute(&buf, map[string]interface{}{ "user": "guest", "role": "viewer", }) fmt.Println(buf.String()) // Output: User: guest, Role: viewer } ``` ### Response #### Success Response (200) - **int64** - The number of bytes written to the writer. - **error** (error) - nil if the execution was successful. #### Response Example ``` Wrote 34 bytes, error: User: guest, Role: viewer ``` ``` -------------------------------- ### NewTemplate - Create a new pre-parsed Template with error handling Source: https://context7.com/valyala/fasttemplate/llms.txt Creates a new pre-parsed Template with custom delimiters, returning an error instead of panicking if the template is malformed. This is the safer alternative to `New` when templates may contain syntax errors. ```APIDOC ## NewTemplate Creates a new pre-parsed Template with custom delimiters, returning an error instead of panicking if the template is malformed. This is the safer alternative to `New` when templates may contain syntax errors. ### Method ```go func NewTemplate(template string, leftDelim string, rightDelim string) (*Template, error) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "log" "github.com/valyala/fasttemplate" ) func main() { template := "Hello, [user]! You won [prize]!" t t, err := fasttemplate.NewTemplate(template, "[", "]") if err != nil { log.Fatalf("error parsing template: %s", err) } s s := t.ExecuteString(map[string]interface{}{ "user": "John", "prize": "$100", }) fmt.Println(s) // Output: Hello, John! You won $100! // Example with malformed template (unclosed tag) _, err = fasttemplate.NewTemplate("Hello [user", "[", "]") if err != nil { fmt.Println("Error:", err) // Output: Error: Cannot find end tag="]" in the template="Hello [user" starting from "user" } } ``` ### Response #### Success Response (200) - **Template** (*Template) - A pointer to the parsed template object. - **error** (error) - nil if the template was parsed successfully. #### Response Example None ``` -------------------------------- ### New - Create a new pre-parsed Template Source: https://context7.com/valyala/fasttemplate/llms.txt Creates a new pre-parsed Template with custom delimiters. This function panics if the template is malformed (e.g., unclosed tags). Use `NewTemplate` for error handling instead of panics. ```APIDOC ## New Creates a new pre-parsed Template with custom delimiters. Panics if the template is malformed (e.g., unclosed tags). Use `NewTemplate` for error handling instead of panics. ### Method ```go func New(template string, leftDelim string, rightDelim string) *Template ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "github.com/valyala/fasttemplate" ) func main() { // Create a template with {{ and }} delimiters template := "http://{{host}}/?q={{query}}&foo={{bar}}{{bar}}" t t := fasttemplate.New(template, "{{", "}}") // Execute with a substitution map s s := t.ExecuteString(map[string]interface{}{ "host": "google.com", "query": "hello%3Dworld", "bar": "foobar", }) fmt.Println(s) // Output: http://google.com/?q=hello%3Dworld&foo=foobarfoobar } ``` ### Response None (This function returns a `*Template` object directly) #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Execute dynamic values with ExecuteFunc Source: https://context7.com/valyala/fasttemplate/llms.txt Uses a callback function to generate replacement values for placeholders dynamically. The TagFunc receives the tag name and writes the result to the provided io.Writer. ```go package main import ( "fmt" "io" "strings" "github.com/valyala/fasttemplate" ) func main() { t := fasttemplate.New("Hello, [user]! You won [prize]!!! [unknown]", "[", "]") result := 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("$100")) default: // Handle unknown tags return w.Write([]byte(fmt.Sprintf("[unknown:%s]", strings.ToUpper(tag)))) } }) fmt.Println(result) // Output: Hello, John! You won $100!!! [unknown:UNKNOWN] } ``` -------------------------------- ### Template.ExecuteString - Substitute placeholders and return as string Source: https://context7.com/valyala/fasttemplate/llms.txt Substitutes template placeholders with corresponding values from a map and returns the result as a string. Supports string, []byte, and TagFunc value types. Missing tags are replaced with empty strings. ```APIDOC ## Template.ExecuteString Substitutes template placeholders with corresponding values from a map and returns the result as a string. Supports string, []byte, and TagFunc value types. Missing tags are replaced with empty strings. ### Method ```go func (t *Template) ExecuteString(vars map[string]interface{}) string ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **vars** (map[string]interface{}) - A map where keys are placeholder names and values are the substitution strings or byte slices. ### Request Example ```go package main import ( "fmt" "github.com/valyala/fasttemplate" ) func main() { t t := fasttemplate.New("Name: {name}, Age: {age}, City: {city}", "{", "}") // String values (convenient) result := t.ExecuteString(map[string]interface{}{ "name": "Alice", "age": "30", // "city" is missing - will be replaced with empty string }) fmt.Println(result) // Output: Name: Alice, Age: 30, City: // Byte slice values (fastest) result = t.ExecuteString(map[string]interface{}{ "name": []byte("Bob"), "age": []byte("25"), "city": []byte("NYC"), }) fmt.Println(result) // Output: Name: Bob, Age: 25, City: NYC } ``` ### Response #### Success Response (200) - **string** - The resulting string with placeholders substituted. #### Response Example ``` Name: Alice, Age: 30, City: Name: Bob, Age: 25, City: NYC ``` ``` -------------------------------- ### ExecuteFunc for Dynamic Tag Generation Source: https://context7.com/valyala/fasttemplate/llms.txt Uses a TagFunc callback to compute placeholder values dynamically during execution. ```go package main import ( "bytes" "fmt" "io" "time" "github.com/valyala/fasttemplate" ) func main() { var buf bytes.Buffer template := "Log: [{timestamp}] [{level}] {message}" fasttemplate.ExecuteFunc(template, "{", "}", &buf, func(w io.Writer, tag string) (int, error) { switch tag { case "timestamp": return w.Write([]byte(time.Now().Format("2006-01-02 15:04:05"))) case "level": return w.Write([]byte("INFO")) case "message": return w.Write([]byte("Application started")) default: return w.Write([]byte("")) } }) fmt.Println(buf.String()) // Output: Log: [2024-01-15 10:30:00] [INFO] Application started } ``` -------------------------------- ### ExecuteStringStd for Partial Substitution Source: https://context7.com/valyala/fasttemplate/llms.txt Performs partial template substitution by preserving unknown placeholders. Useful for multi-pass template rendering. ```go package main import ( "fmt" "github.com/valyala/fasttemplate" ) func main() { template := "Server: {server}, Port: {port}, Status: {status}" // First pass - substitute only known values partial := fasttemplate.ExecuteStringStd(template, "{", "}", map[string]interface{}{ "server": "localhost", }) fmt.Println(partial) // Output: Server: localhost, Port: {port}, Status: {status} // Second pass - substitute remaining values final := fasttemplate.ExecuteStringStd(partial, "{", "}", map[string]interface{}{ "port": "8080", "status": "running", }) fmt.Println(final) // Output: Server: localhost, Port: 8080, Status: running } ``` -------------------------------- ### Execute Template with Function for Tag Values Source: https://github.com/valyala/fasttemplate/blob/master/README.md Use ExecuteFuncString when tag values require dynamic generation or complex logic. The provided function handles tag resolution and writing to the output. Errors during parsing should be handled. ```go 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) ``` -------------------------------- ### Perform one-off substitution with ExecuteString Source: https://context7.com/valyala/fasttemplate/llms.txt A standalone function for scenarios where templates change too frequently to justify pre-parsing. This avoids the overhead of creating a Template object. ```go package main import ( "fmt" "github.com/valyala/fasttemplate" ) func main() { // For dynamic templates that change frequently, use standalone functions templates := []string{ "Hello, {name}!", "Welcome back, {name}!", "Goodbye, {name}!", } values := map[string]interface{}{"name": "World"} for _, tmpl := range templates { result := fasttemplate.ExecuteString(tmpl, "{", "}", values) fmt.Println(result) } // Output: // Hello, World! // Welcome back, World! // Goodbye, World! } ``` -------------------------------- ### Template.ExecuteStringStd - Substitute known placeholders, preserve unknown Source: https://context7.com/valyala/fasttemplate/llms.txt Works like ExecuteString but preserves unknown placeholders instead of replacing them with empty strings. This is useful as a drop-in replacement for strings.Replacer when partial substitution is needed. ```APIDOC ## Template.ExecuteStringStd Works like ExecuteString but preserves unknown placeholders instead of replacing them with empty strings. This is useful as a drop-in replacement for strings.Replacer when partial substitution is needed. ### Method ```go func (t *Template) ExecuteStringStd(vars map[string]interface{}) string ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **vars** (map[string]interface{}) - A map where keys are placeholder names and values are the substitution strings or byte slices. ### Request Example ```go package main import ( "fmt" "github.com/valyala/fasttemplate" ) func main() { t t := fasttemplate.New("Hello {user}! Your code is {code}. Status: {status}", "{", "}") // Only substitute known values, keep unknown placeholders intact result := t.ExecuteStringStd(map[string]interface{}{ "user": "Alice", // "code" and "status" are not provided }) fmt.Println(result) // Output: Hello Alice! Your code is {code}. Status: {status} } ``` ### Response #### Success Response (200) - **string** - The resulting string with known placeholders substituted and unknown ones preserved. #### Response Example ``` Hello Alice! Your code is {code}. Status: {status} ``` ``` -------------------------------- ### Template.ExecuteFuncString Source: https://context7.com/valyala/fasttemplate/llms.txt Executes a template by calling a custom function for each placeholder, allowing for dynamic value generation. The TagFunc receives the tag name and writes the replacement value to the provided writer. ```APIDOC ## Template.ExecuteFuncString ### Description Calls a custom function for each placeholder, allowing dynamic value generation. The TagFunc receives the tag name and writes the replacement value. ### Method `ExecuteFuncString` ### Parameters None directly on the method, but it accepts a `TagFunc` as an argument. ### TagFunc Signature `func(w io.Writer, tag string) (int, error)` - `w`: The writer to which the replacement value should be written. - `tag`: The name of the tag found in the template. ### Request Example ```go package main import ( "fmt" "io" "strings" "github.com/valyala/fasttemplate" ) func main() { t := fasttemplate.New("Hello, [user]! You won [prize]!!! [unknown]", "[", "]") result := 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("$100")) default: // Handle unknown tags return w.Write([]byte(fmt.Sprintf("[unknown:%s]", strings.ToUpper(tag)))) } }) fmt.Println(result) // Output: Hello, John! You won $100!!! [unknown:UNKNOWN] } ``` ### Response Returns the processed string with placeholders replaced by values generated by the `TagFunc`. ``` -------------------------------- ### Use TagFunc for dynamic substitution Source: https://context7.com/valyala/fasttemplate/llms.txt Allows embedding logic directly into the substitution map. TagFunc implementations must be safe for concurrent use. ```go package main import ( "fmt" "io" "net/url" "github.com/valyala/fasttemplate" ) func main() { t := fasttemplate.New("http://{{host}}/?q={{query}}&items={{items}}", "{{", "}}") items := []string{"apple", "banana", "cherry"} result := t.ExecuteString(map[string]interface{}{ "host": "example.com", // TagFunc for URL encoding "query": fasttemplate.TagFunc(func(w io.Writer, tag string) (int, error) { return w.Write([]byte(url.QueryEscape("search term"))) }), // TagFunc for joining multiple items "items": fasttemplate.TagFunc(func(w io.Writer, tag string) (int, error) { var total int for i, item := range items { if i > 0 { n, _ := w.Write([]byte(",")) total += n } n, err := w.Write([]byte(item)) total += n if err != nil { return total, err } } return total, nil }), }) fmt.Println(result) // Output: http://example.com/?q=search+term&items=apple,banana,cherry } ``` -------------------------------- ### ExecuteString (Standalone) Source: https://context7.com/valyala/fasttemplate/llms.txt A standalone function for one-off template substitution without pre-parsing. It is optimized for templates that change frequently, where the overhead of pre-parsing is not beneficial. ```APIDOC ## ExecuteString (Standalone) ### Description Standalone function for one-off template substitution without pre-parsing. Optimized for constantly changing templates where pre-parsing overhead is not worthwhile. ### Method `fasttemplate.ExecuteString` ### Parameters - **template** (string) - Required - The template string to process. - **leftDelim** (string) - Required - The left delimiter for tags. - **rightDelim** (string) - Required - The right delimiter for tags. - **vars** (map[string]interface{}) - Required - A map of variable names to their values. ### Request Example ```go package main import ( "fmt" "github.com/valyala/fasttemplate" ) func main() { // For dynamic templates that change frequently, use standalone functions templates := []string{ "Hello, {name}!", "Welcome back, {name}!", "Goodbye, {name}!", } values := map[string]interface{}{"name": "World"} for _, tmpl := range templates { result := fasttemplate.ExecuteString(tmpl, "{", "}", values) fmt.Println(result) } // Output: // Hello, World! // Welcome back, World! // Goodbye, World! } ``` ### Response Returns the processed string with placeholders replaced by the corresponding values from the `vars` map. ``` -------------------------------- ### Template.ExecuteFuncStringWithErr Source: https://context7.com/valyala/fasttemplate/llms.txt Similar to ExecuteFuncString, but returns errors instead of panicking. This is useful when the TagFunc might encounter errors during value generation. ```APIDOC ## Template.ExecuteFuncStringWithErr ### Description Like ExecuteFuncString but returns errors instead of panicking. Useful when the TagFunc may encounter errors during value generation. ### Method `ExecuteFuncStringWithErr` ### Parameters None directly on the method, but it accepts a `TagFunc` as an argument. ### TagFunc Signature `func(w io.Writer, tag string) (int, error)` - `w`: The writer to which the replacement value should be written. - `tag`: The name of the tag found in the template. ### Request Example ```go package main import ( "errors" "fmt" "io" "github.com/valyala/fasttemplate" ) func main() { t, _ := fasttemplate.NewTemplate("{a} is {b}'s best friend", "{", "}") // Simulate an error condition result, err := t.ExecuteFuncStringWithErr(func(w io.Writer, tag string) (int, error) { if tag == "a" { return w.Write([]byte("Alice")) } if tag == "b" { return 0, errors.New("database connection failed") } return 0, nil }) if err != nil { fmt.Println("Error:", err) // Output: Error: database connection failed } // Successful execution result, err = t.ExecuteFuncStringWithErr(func(w io.Writer, tag string) (int, error) { if tag == "a" { return w.Write([]byte("Alice")) } return w.Write([]byte("Bob")) }) fmt.Println(result) // Output: Alice is Bob's best friend } ``` ### Response Returns the processed string and an error if one occurred during execution. If successful, the error will be `nil`. ``` -------------------------------- ### Reuse templates with Reset Source: https://context7.com/valyala/fasttemplate/llms.txt Resets an existing Template instance to parse a new string, which helps reduce memory allocations. Do not call this method while other goroutines are using the template. ```go package main import ( "fmt" "github.com/valyala/fasttemplate" ) func main() { t := fasttemplate.New("foo{bar}baz", "{", "}") result := t.ExecuteString(map[string]interface{}{"bar": "111"}) fmt.Println(result) // Output: foo111baz // Reset to a new template with different delimiters err := t.Reset("[xxx]yyy[zz]", "[", "]") if err != nil { fmt.Println("Error:", err) return } result = t.ExecuteString(map[string]interface{}{"xxx": "AAA", "zz": "BBB"}) fmt.Println(result) // Output: AAAyyyBBB // Reset with malformed template returns error err = t.Reset("[unclosed", "[", "]") if err != nil { fmt.Println("Reset error:", err) // Output: Reset error: Cannot find end tag="]" in the template="[unclosed" starting from "unclosed" } } ``` -------------------------------- ### Execute with error handling using ExecuteFuncStringWithErr Source: https://context7.com/valyala/fasttemplate/llms.txt Allows the TagFunc to return errors during value generation, preventing panics. Useful for operations that may fail, such as database lookups. ```go package main import ( "errors" "fmt" "io" "github.com/valyala/fasttemplate" ) func main() { t, _ := fasttemplate.NewTemplate("{a} is {b}'s best friend", "{", "}") // Simulate an error condition result, err := t.ExecuteFuncStringWithErr(func(w io.Writer, tag string) (int, error) { if tag == "a" { return w.Write([]byte("Alice")) } if tag == "b" { return 0, errors.New("database connection failed") } return 0, nil }) if err != nil { fmt.Println("Error:", err) // Output: Error: database connection failed } // Successful execution result, err = t.ExecuteFuncStringWithErr(func(w io.Writer, tag string) (int, error) { if tag == "a" { return w.Write([]byte("Alice")) } return w.Write([]byte("Bob")) }) fmt.Println(result) // Output: Alice is Bob's best friend } ``` -------------------------------- ### Template.Reset Source: https://context7.com/valyala/fasttemplate/llms.txt Resets an existing Template to parse a new template string. This allows for object reuse and reduces memory allocations. It must not be called concurrently with other goroutines executing the template. ```APIDOC ## Template.Reset ### Description Resets an existing Template to parse a new template string, allowing object reuse and reducing allocations. Must not be called while other goroutines are executing the template. ### Method `Reset` ### Parameters - **template** (string) - Required - The new template string to parse. - **leftDelim** (string) - Required - The left delimiter for tags. - **rightDelim** (string) - Required - The right delimiter for tags. ### Request Example ```go package main import ( "fmt" "github.com/valyala/fasttemplate" ) func main() { t := fasttemplate.New("foo{bar}baz", "{", "}") result := t.ExecuteString(map[string]interface{}{"bar": "111"}) fmt.Println(result) // Output: foo111baz // Reset to a new template with different delimiters err := t.Reset("[xxx]yyy[zz]", "[", "]") if err != nil { fmt.Println("Error:", err) return } result = t.ExecuteString(map[string]interface{}{"xxx": "AAA", "zz": "BBB"}) fmt.Println(result) // Output: AAAyyyBBB // Reset with malformed template returns error err = t.Reset("[unclosed", "[", "]") if err != nil { fmt.Println("Reset error:", err) // Output: Reset error: Cannot find end tag="]" in the template="[unclosed" starting from "unclosed" } } ``` ### Response Returns an error if the new template string is malformed or if delimiters are invalid. Otherwise, returns `nil`. ``` -------------------------------- ### TagFunc Type Source: https://context7.com/valyala/fasttemplate/llms.txt A function type that can be used as a value in substitution maps. It enables dynamic, computed values for placeholders and must be safe to call from concurrent goroutines. ```APIDOC ## TagFunc ### Description A function type that can be used as a value in substitution maps. Enables dynamic, computed values for placeholders. TagFunc must be safe to call from concurrent goroutines. ### Type Definition `type TagFunc func(w io.Writer, tag string) (int, error)` ### Parameters - `w` (io.Writer): The writer to which the replacement value should be written. - `tag` (string): The name of the tag found in the template. ### Return Values - `int`: The number of bytes written. - `error`: An error if one occurred during writing. ### Usage Example ```go package main import ( "fmt" "io" "net/url" "github.com/valyala/fasttemplate" ) func main() { t := fasttemplate.New("http://{{host}}/?q={{query}}&items={{items}}", "{{", "}}") items := []string{"apple", "banana", "cherry"} result := t.ExecuteString(map[string]interface{}{ "host": "example.com", // TagFunc for URL encoding "query": fasttemplate.TagFunc(func(w io.Writer, tag string) (int, error) { return w.Write([]byte(url.QueryEscape("search term"))) }), // TagFunc for joining multiple items "items": fasttemplate.TagFunc(func(w io.Writer, tag string) (int, error) { var total int for i, item := range items { if i > 0 { n, _ := w.Write([]byte(",")) total += n } n, err := w.Write([]byte(item)) total += n if err != nil { return total, err } } return total, nil }), }) fmt.Println(result) // Output: http://example.com/?q=search+term&items=apple,banana,cherry } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.