dqt20140129 2017-01-25 15:55
浏览 156
已采纳

如何使用Go将多个字符串解析为模板?

Is there a simple way like template.ParseFiles("base.html", "home.html") but for strings to build a template from a set of strings?

I have a base template and a list of pages templates (all as strings) that I want to build on top of base template.

I figured out how to merge them, but I my solution is quite verbose and doesn't look elegant enough, even though working.

  • 写回答

2条回答 默认 最新

  • duanren9163 2017-01-25 16:11
    关注

    You may create a new, empty template using template.New() function. Then you may use the Template.New() method to create a new, empty, associated template. And you may parse "into" this using the Template.Parse() method.

    Here's how it could look like:

    func parseTemplates(templs ...string) (t *template.Template, err error) {
        t = template.New("_all")
    
        for i, templ := range templs {
            if _, err = t.New(fmt.Sprint("_", i)).Parse(templ); err != nil {
                return
            }
        }
    
        return
    }
    

    Testing it:

    t, err := parseTemplates(
        `{{define "one"}}I'm #1.{{end}}`,
        `{{define "two"}}I'm #2, including #1: {{template "one" .}}{{end}}`,
    )
    if err != nil {
        panic(err)
    }
    
    if err = t.ExecuteTemplate(os.Stdout, "two", nil); err != nil {
        panic(err)
    }
    

    Output (try it on the Go Playground):

    I'm #2, including #1: I'm #1.
    

    Also see related question: Go template name

    Note

    While we could call the Template.Parse() method on a single template multiple times, and it would parse multiple named templates properly, it is still advisable to acquire a new template.Template for each by calling Template.New(). Because if the template texts have content outside of named templates, they will be overwritten and only the last would be retained. For example: abc {{define "one"}}no 1{{end}}. The static text "abc" would be lost by a subsequent Template.Parse() call.

    This is also noted in the doc of Template.Parse():

    (In multiple calls to Parse with the same receiver template, only one call can contain text other than space, comments, and template definitions.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器