gpt4 book ai didi

go - 带字符串的模板继承

转载 作者:IT王子 更新时间:2023-10-29 02:35:39 26 4
gpt4 key购买 nike

我有一些我解析的小 .html 文件:

template.Must(
template.New("test").
ParseFiles(
"templates/f1.html",
"templates/f2.html",
"templates/f3.html",
),
)

这些都是非常小的文件,例如,我想让这些只是字符串以使我的代码更容易,但是我如何使用字符串进行相同类型的模板继承?我所看到的只是 Parse 方法,但它只需要 1 个字符串:

func (t *Template) Parse(text string) (*Template, error)

我的字符串:

f1 := `Hi there {{template "content" .}}`
f2 := `{{define "content"}}bob {{template "content2" .}}{{end}}`
f3 := `{{define "content2"}}ross{{end}}`

不确定如何让这些“一起玩”。 (这是我正在做的事情的一个简化示例,这些字符串在多个地方使用,因此将它们全部组合为 1 个没有意义)。

最佳答案

尝试:

const (
f1 = `Hi there {{template "content" .}}`
f2 = `{{define "content"}}bob {{template "content2" .}}{{end}}`
f3 = `{{define "content2"}}ross{{end}}`
)

func main() {
t := template.New("test")

t.Parse(f1)
t.Parse(f2)
t.Parse(f3)

t.Execute(os.Stdout, nil)
}

产生:嗨,鲍勃罗斯

playground版本。

关于go - 带字符串的模板继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54682505/

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