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

How to Concatenate Strings in Go Templates?

Barbara Streisand
Release: 2024-11-08 18:24:02
Original
253 people have browsed it

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 }}
Copy after login

$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") }}
Copy after login

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 }}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template