如何修剪 Go 模板中的空格

Kbo*_*oyz 2 go go-templates

我想修剪 Go 模板中的空白。我该怎么做呢?

例子:

 {{ $title = " My Title of the product " }} 
 
 // Print the trim string here
 <h1>{{ $title }}</h1>
Run Code Online (Sandbox Code Playgroud)

mko*_*iva 6

模板内没有任何内置内容可以为您修剪字符串“管道”,但是strings.TrimSpace如果您使用该Funcs方法将其提供给该模板,则可以在模板内使用该函数。

var str = `{{ $title := " My Title of the product " }}

// Print the trim string here
<h1>{{ trim $title }}</h1>`

t := template.Must(template.New("t").Funcs(template.FuncMap{
    "trim": strings.TrimSpace,
}).Parse(str))
Run Code Online (Sandbox Code Playgroud)

https://play.golang.org/p/g0T7shJbDVw