Skip to content

text/template: can invoke method of pipeline result value #28577

@mei-rune

Description

@mei-rune

can invoke method of pipeline result value

package main

import (
 "fmt"
  "bytes"
  "html/template"
)


type TextField struct {
    name string
    value string
}

func (field *TextField) SetValue( value string) *TextField {
   field.value = value
   return field
}

func (field *TextField) Render() template.HTML {
  return  template.HTML(`<input type="text" name="`+field.name+`">`+field.value+`</input>`)
}

func NewTextField(name string) *TextField  {
   return &TextField{name: name}
}

var funcs = template.FuncMap{
 "text_field": NewTextField,
 }


func main() {
     txt := `{{text_field "username" |SetValue .value |Render }}`

      var buf bytes.Buffer
      var tpl, _ = template.New("main").Funcs(funcs).Parse(txt)
     tpl.Execute(&buf, map[string]interface{}{"value": "world"});
	fmt.Println(buf.String())
	//Output <input type="text" name="username">world</input>
}

text_field return *TextField ptr,
"|SetValue .value" will invoke "func (field *TextField) SetValue( value string)"
"|Render" will invoke "func (field *TextField) Render()"

like

// {{text_field "username" |SetValue .value |Render }}
NewTextField("username").SetValue(xxxx).Render()

if method isnot exists then execute old behaviour.

My English is poor.
我的意恩是
现在模板将符号 '|' 之前的执行结果作来下一个方法(function)的最后一个参数, 那能不能将 '|' 后的方法作为前一次结果的成员函数(method),

Metadata

Metadata

Assignees

No one assigned

    Labels

    FeatureRequestIssues asking for a new feature that does not need a proposal.FrozenDueToAgeNeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions