mirror of
https://github.com/golang/go
synced 2024-11-13 17:30:24 -07:00
text/template: evaluate function fields
Just an oversight they didn't work and easy to address. Fixes #3025. R=golang-dev, dsymonds CC=golang-dev https://golang.org/cl/5656059
This commit is contained in:
parent
9a44560033
commit
aca8071fd5
@ -419,10 +419,14 @@ func (s *state) evalField(dot reflect.Value, fieldName string, args []parse.Node
|
||||
tField, ok := receiver.Type().FieldByName(fieldName)
|
||||
if ok {
|
||||
field := receiver.FieldByIndex(tField.Index)
|
||||
if hasArgs {
|
||||
s.errorf("%s is not a method but has arguments", fieldName)
|
||||
}
|
||||
if tField.PkgPath == "" { // field is exported
|
||||
// If it's a function, we must call it.
|
||||
if field.Type().Kind() == reflect.Func {
|
||||
return s.evalCall(dot, field, fieldName, args, final)
|
||||
}
|
||||
if hasArgs {
|
||||
s.errorf("%s is not a method or function but has arguments", fieldName)
|
||||
}
|
||||
return field
|
||||
}
|
||||
}
|
||||
|
@ -59,6 +59,8 @@ type T struct {
|
||||
PI *int
|
||||
PSI *[]int
|
||||
NIL *int
|
||||
// Function (not method)
|
||||
Func func(...string) string
|
||||
// Template to test evaluation of templates.
|
||||
Tmpl *Template
|
||||
}
|
||||
@ -118,6 +120,7 @@ var tVal = &T{
|
||||
Err: errors.New("erroozle"),
|
||||
PI: newInt(23),
|
||||
PSI: newIntSlice(21, 22, 23),
|
||||
Func: func(s ...string) string { return fmt.Sprint("<", strings.Join(s, "+"), ">") },
|
||||
Tmpl: Must(New("x").Parse("test template")), // "x" is the value of .X
|
||||
}
|
||||
|
||||
@ -297,8 +300,13 @@ var execTests = []execTest{
|
||||
"{{with $x := .}}{{with .SI}}{{$.GetU.TrueFalse $.True}}{{end}}{{end}}",
|
||||
"true", tVal, true},
|
||||
|
||||
// Function call
|
||||
{".Func", "-{{.Func}}-", "-<>-", tVal, true},
|
||||
{".Func2", "-{{.Func `he` `llo`}}-", "-<he+llo>-", tVal, true},
|
||||
|
||||
// Pipelines.
|
||||
{"pipeline", "-{{.Method0 | .Method2 .U16}}-", "-Method2: 16 M0-", tVal, true},
|
||||
{"pipeline func", "-{{.Func `llo` | .Func `he` }}-", "-<he+<llo>>-", tVal, true},
|
||||
|
||||
// If.
|
||||
{"if true", "{{if true}}TRUE{{end}}", "TRUE", tVal, true},
|
||||
|
Loading…
Reference in New Issue
Block a user