Reputation: 189
I would like to trim white spaces in Go templates. How would I do that?
Example:
{{ $title = " My Title of the product " }}
// Print the trim string here
<h1>{{ $title }}</h1>
Upvotes: 2
Views: 10030
Reputation: 38243
There's nothing built in that will trim string "pipelines" for you inside a template, however you could use the strings.TrimSpace
function inside a template if you provide it to that template with the Funcs
method.
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.
Upvotes: 6
Reputation: 44
if you want "My Title of the product" to MyTitleoftheproduct you can use that func
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
}
Upvotes: 0