gpt4 book ai didi

如果不匹配,Golang 模板将忽略

转载 作者:IT王子 更新时间:2023-10-29 02:17:07 28 4
gpt4 key购买 nike

我正在尝试转换 golang 模板,如果未找到匹配项,则允许忽略。这可能吗?

Playground

package main

import (
"bytes"
"fmt"
"text/template"
)
type Person struct {
Name string
Age int
}
type Info struct {
Name string
Id int
}

func main() {
msg := "Hello {{ .Id }} With name {{ .Name }}"
p := Person{Name: "John", Age: 24}
i := Info{Name: "none", Id: 5}

t := template.New("My template")
t, _ = t.Parse(msg)

buf := new(bytes.Buffer)
t.Execute(buf, p)
fmt.Println(buf.String())

buf = new(bytes.Buffer)
t.Execute(buf, i)
fmt.Println(buf.String())
}

我想打印这个

你好 {{ .Id }} 名字叫 JohnHello 5 With name none

最佳答案

如果你想让它只在非空字符串时打印 name:

"Hello {{ .Id }} With name {{ if .Name }}{{ .Name }}{{ end }}"

否则,如果你想打印其他东西:

"Hello {{ .Id }} With name {{ if .Name }}{{ .Name }}{{ else }}none!{{ end }}"

Playground - 另见 the comparison operators用于 html/模板和文本/模板。

关于如果不匹配,Golang 模板将忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25070414/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com