Home >Backend Development >Golang >How to Concatenate Strings in Go Templates?
C
When working with text/template in Go, it's often necessary to concatenate strings to build dynamic content. However, unlike many other programming languages, Go templates do not support string concatenation operators.
Consider the following example:
{{ $var := printf "%s%s" "x" "y" }} {{ TestFunc $var }}
$var contains the concatenated string "xy", but TestFunc only receives the string "y" because the printf function is executed separately from the TestFunc call.
There are a few ways to concatenate strings efficiently in Go templates. One method is to use the printf function as in the example above. Another option is to combine multiple template expressions into a single one:
{{ TestFunc (printf "%s%s" "x" "y") }}
If you frequently concatenate strings before calling TestFunc, it can be more efficient to modify TestFunc to handle the concatenation:
func TestFunc(strs ...string) string { return strings.Trim(strings.Join(strs, ""), " ") } {{ TestFunc "x" $var }}
The above is the detailed content of How to Concatenate Strings in Go Templates?. For more information, please follow other related articles on the PHP Chinese website!