代码之家  ›  专栏  ›  技术社区  ›  Kurt Peek

在Go模板中,如何仅在字符串值非空的情况下添加一行?

  •  1
  • Kurt Peek  · 技术社区  · 5 月前

    我想呈现一个包含特定字符串字段的结构体的模板,比如 Restaurant 用一个 Name ,如果 姓名 如果非空,则打印在一行上,但如果为空,则该行不存在。到目前为止,我已经试过了

    package main
    
    import (
        "os"
        "text/template"
    )
    
    type Restaurant struct {
        Name string
    }
    
    func main() {
        tmpl, err := template.New("test").Parse(`The restaurant is:
    {{if .Name }}{{.Name}}{{ end }}
    The end.
    `)
        if err != nil {
            panic(err)
        }
    
        if err := tmpl.Execute(os.Stdout, Restaurant{Name: ""}); err != nil {
            panic(err)
        }
    }
    

    这张照片

    The restaurant is:
    
    The end.
    

    但是,在这种情况下,我希望省略中间的空行:

    The restaurant is:
    The end.
    

    然而,当名称非空时,我希望行存在:如果我使用 Restaurant{Name: "Itria"} tmpl.Execute 参数,输出应该是

    The restaurant is:
    Itria
    The end.
    

    我读过 https://pkg.go.dev/text/template#hdr-Text_and_spaces 但我不清楚如何使用动作前后的减号分隔符来实现这一点。

    2 回复  |  直到 5 月前
        1
  •  1
  •   icza    5 月前

    如果满足以下条件,您希望换行符有条件地呈现 .Name 不是空的。因此,在 {{if}} 块,并且不在后面呈现(留下)换行符 {{if}} 块(试试 Go Playground ):

        tmpl, err := template.New("test").Parse(`The restaurant is:
    {{if .Name }}{{.Name}}
    {{end}}The end.
    `)
    

    或者另一种解决方案(在 Go Playground ):

        tmpl, err := template.New("test").Parse(`The restaurant is:
    {{if .Name }}{{.Name}}
    {{ end -}}
    The end.
    `)
    
        2
  •  1
  •   Burak Serdar    5 月前

    一种方法是:

    tmpl, err := template.New("test").Parse(`The restaurant is:
    {{- if .Name }}
    {{.Name}}{{ end }}
    The end.
    `)
    

    这会在if块的末尾保留一个换行符,但会清除它之前的换行符。