Home >Backend Development >Golang >How to Concatenate Strings in Go Templates?

How to Concatenate Strings in Go Templates?

Barbara Streisand
Barbara StreisandOriginal
2024-11-08 18:24:02281browse

How to Concatenate Strings in Go Templates?

C

Concatenating Strings in Go Templates

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.

Issue

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.

Solution

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn