首页 > 解决方案 > 如何修剪 Go 模板中的空白

问题描述

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

例子:

 {{ $title = " My Title of the product " }} 
 
 // Print the trim string here
 <h1>{{ $title }}</h1>

标签: gogo-templates

解决方案


没有任何内置功能可以在模板内为您修剪字符串“管道”,但是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))

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


推荐阅读