代码之家  ›  专栏  ›  技术社区  ›  user_78361084

带字符串的模板继承

go
  •  0
  • user_78361084  · 技术社区  · 5 年前

    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是没有意义的)。

    1 回复  |  直到 5 年前
        1
  •  2
  •   colm.anseo    5 年前

    尝试:

    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)
    }
    

    生产: Hi there bob ross

    playground 版本。