【问题标题】:How to trim white spaces in Go templates如何修剪 Go 模板中的空白
【发布时间】:2020-06-23 22:06:35
【问题描述】:

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

例子:

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

【问题讨论】:

  • "trim whitespace" 通常意味着从字符串的开头和结尾删除空格。字符串的开头或结尾没有空格——即使有,在 HTML 输出中也没有关系,因为多余的空格会被忽略。所以你的问题很不清楚。
  • 如果您正在寻找如何删除模板 actions 之间的空白,那么您可以使用 - 文档中的 here

标签: go go-templates


【解决方案1】:

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

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.

【讨论】:

    【解决方案2】:

    如果你想要“我的产品标题”到 MyTitleoftheproduct,你可以使用那个函数

    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
    }
    

    【讨论】:

    • 这不适用于问题所问的 go 模板。
    • 这也是不正确的,因为它只在输入包含文字空间而不是任何空格时才有效,并且它只删除引用文字空间的Unicode字符,这不是所有的空格。它也非常低效。
    猜你喜欢
    • 2021-08-31
    • 2022-06-30
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    • 2017-03-16
    • 1970-01-01
    相关资源
    最近更新 更多