如何修剪Go模板中的空白

如何修剪Go模板中的空白,go,go-templates,Go,Go Templates,我想修剪去模板中的空白。我该怎么做 例如: {{ $title = " My Title of the product " }} // Print the trim string here <h1>{{ $title }}</h1> {{$title=“我的产品名称”} //在这里打印修剪字符串 {{$title}} 如果您想将“我的产品标题”添加到我的产品标题中,您可以使用该功能 package main import ( &

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

例如:

 {{ $title = " My Title of the product " }} 
 
 // Print the trim string here
 <h1>{{ $title }}</h1>
{{$title=“我的产品名称”}
//在这里打印修剪字符串
{{$title}}
如果您想将“我的产品标题”添加到我的产品标题中,您可以使用该功能

package main

import (
    "fmt"
     "strings"
     "strconv"
)

func main(){
    s:= "a b c d "
    n:=trimW(s)
    fmt.Println(n)
    //abcd
}

func trimW(l string) string {
    var c []string
    if strings.Contains(l, " ") {
         
        for _, str := range l {
             
            if strconv.QuoteRune(str) != "' '" {
                c =append(c,string(str))
            }
         
        }
        l = strings.Join(c,"")
    }
    return l
}

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

var str=`{{$title:=“产品的我的标题”}}
//在这里打印修剪字符串
{{trim$title}}`
t:=template.Must(template.New(“t”).Funcs(template.FuncMap{
“trim”:strings.TrimSpace,
}).Parse(str))

.

我不太清楚您期望的输出或结果。请您将这些信息添加到您的问题中好吗?“修剪空白”通常意味着从字符串的开头和结尾删除空白。字符串的开头或结尾没有空格——即使有,在HTML输出中也不重要,多余的空格会被忽略。因此,您的问题非常不清楚。如果您正在寻找如何删除模板操作之间的空白,那么您可以使用文档中的
-
。哦,很抱歉。我编辑了我的帖子。我的意思是删除字符串上的空格这不适用于问题所涉及的go模板。它也不正确,因为它只适用于输入包含文本空间而不是任何空格的情况,并且它只删除引用到文本空间的Unicode字符,而文本空间不全是空格。它的效率也非常低。
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))