go - 如何在Go模板中修剪空白

标签 go go-templates

我想修剪Go模板中的空白。我该怎么办?
例子:

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

最佳答案

内置的任何东西都不会在模板内为您修剪字符串“管道”,但是,如果您使用 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

关于go - 如何在Go模板中修剪空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62531276/

相关文章:

string - 从golang中的字节数组解压gzip

go - 无法安装 go 软件包

html - 使用go模板解析页面中显示为纯文本的HTML代码

Golang 模板 - 使用模板变量作为范围循环内的全局变量

go - 在匿名映射中指定字段名称

http - MIME ParseMediaType 在多部分边界上失败

go - 如何链接HTML

go - 如何使用 golang 服务 angular?

templates - 如何将变量传递给模板并在 beego 中接收变量

go - 如何使用 HTML 和 CSS 设置 Go 错误的样式?