How can I join two strings in go templates?

ぐ巨炮叔叔 提交于 2021-01-04 05:38:06

问题


I found this documentation to join two strings, but this doesn't work inside go templates.

Is there a way to join strings inside a go template?


回答1:


Write a function to join the strings and add it to the template func map:

func join(s ...string) string {
    // first arg is sep, remaining args are strings to join
    return strings.Join(s[1:], s[0])
}

Add the function to template before parsing:

t, err := template.New(name).Funcs(template.FuncMap{"join": join}).Parse(text)

Use it in the template like this:

{{$x := join ", " "hello" "world"}}

playground example

I assign to variable $x to show how use the function result in a template expression. The result can be used directly as an argument to another function without assigning to a variable.

If your goal is to join two strings in the output, then you can use {{a}}sep{{b}} where a and b are the strings and sep is the separator.

Use the print function to join strings with an empty separator:

 {{$x := print a b}}

playground example




回答2:


Use a combination of delimit and slice, e.g.

{{ delimit (slice "foo" "bar" "buzz") ", " }}
<!-- returns the string "foo, bar, buzz" -->

Originally from the gohugo docs




回答3:


In the template example https://golang.org/src/text/template/example_test.go they show you how to do this.

In summary:

var funcs = template.FuncMap{"join": strings.Join}
...
masterTmpl, err := template.New("master").Funcs(funcs).Parse(master)

There's some other neat tricks in the example too.



来源:https://stackoverflow.com/questions/39023060/how-can-i-join-two-strings-in-go-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!