dtf54486
dtf54486
2016-01-09 03:55

go'Template.Execute'如何读取其匿名结构的参数字段?

  • IT行业问题
  • 计算机技术
  • it技术
  • 编程语言问答
  • 互联网问答
已采纳

In coding with Go, with html.template package, template.Execute is called.
I have a question, how could it read the field of anonymous structure of its parameter.
I read the source code, but it doesn't make sense. I don't have an idea.

/usr/local/go/src/html/template/tempalte.go L.78

type Template struct {
    ...
    text *template.Template
    ...
}

// escape escapes all associated templates.
func (t *Template) escape() error {
    t.nameSpace.mu.Lock()
    defer t.nameSpace.mu.Unlock()
    if t.escapeErr == nil {
        if t.Tree == nil {
            return fmt.Errorf("template: %q is an incomplete or empty template%s", t.Name(), t.text.DefinedTemplates())
        }
        if err := escapeTemplate(t, t.text.Root, t.Name()); err != nil {
            return err 
        }
    } else if t.escapeErr != escapeOK {
        return t.escapeErr
    }   
    return nil 
}

// Execute applies a parsed template to the specified data object,
// writing the output to wr.
// If an error occurs executing the template or writing its output,
// execution stops, but partial results may already have been written to
// the output writer.
// A template may be executed safely in parallel.
func (t *Template) Execute(wr io.Writer, data interface{}) error {
    if err := t.escape(); err != nil {
        return err 
    }   
    return t.text.Execute(wr, data)
}

GoDoc demonstrates its usage, calling Execute with its interface{} paramter like this;

data := struct {
    Title string
    Items []string
}{
    Title: "My another page",
    Items: []string{},
}


err = t.Execute(os.Stdout, data)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douyan5481 douyan5481 5年前

    If you look at the return of Execute it calls t.text.Execute which is calling this function from the text/template package:

       132  func (t *Template) Execute(wr io.Writer, data interface{}) (err error) {
       133      defer errRecover(&err)
       134      value := reflect.ValueOf(data)
       135      state := &state{
       136          tmpl: t,
       137          wr:   wr,
       138          vars: []variable{{"$", value}},
       139      }
       140      if t.Tree == nil || t.Root == nil {
       141          state.errorf("%q is an incomplete or empty template%s", t.Name(), t.DefinedTemplates())
       142      }
       143      state.walk(value, t.Root)
       144      return
       145  }
    

    So it will use the reflect package to parse the variables into the template.

    Here's a little example of whats happening: http://play.golang.org/p/ih1Ei33NsO

    点赞 评论 复制链接分享

为你推荐