15

I use "text/template" module.

I have struct like this to parse XML from Blogger

type Media struct {
    ThumbnailUrl string `xml:"url,attr"`
}


type Entry struct {
    ID string `xml:"id"`
    Published Date `xml:"published"`
    Updated Date `xml:"updated"`
    Draft Draft `xml:"control>draft"`
    Title string `xml:"title"`
    Content string `xml:"content"`
    Tags Tags `xml:"category"`
    Author Author `xml:"author"`
    Media Media `xml:"thumbnail"`
    Extra string
}

Then I create Go Template like this

[image]
    src = "{{ replace .Media.ThumbnailUrl 's72-c' 's1600' }}"
    link = ""
    thumblink = "{{ .Media.ThumbnailUrl }}"
    alt = ""
    title = ""
    author = ""
    license = ""
    licenseLink = ""

The replace function not defined. I want to replace URL from {{ .Media.ThumbnailUrl }}

For example:

from this URL

https://2.bp.blogspot.com/-DEeRanrBa6s/WGWGwA2qW5I/AAAAAAAADg4/feGUc-g9rXc9B7hXpKr0ecG9UOMXU3_VQCK4B/s72-c/pemrograman%2Bjavascript%2B-%2Bpetanikode.png

To this URL

https://2.bp.blogspot.com/-DEeRanrBa6s/WGWGwA2qW5I/AAAAAAAADg4/feGUc-g9rXc9B7hXpKr0ecG9UOMXU3_VQCK4B/s1600/pemrograman%2Bjavascript%2B-%2Bpetanikode.png

Dian
  • 470
  • 1
  • 6
  • 20
  • Uh, set the variable of ThumbnailUrl to the url you want in whatever is calling the template? I don't think `replace` is a thing in go templates. – Alexander Kleinhans Jan 14 '17 at 07:39

1 Answers1

11

You can write a helper view function like this

func replace(input, from,to string) string {
    return strings.Replace(input,from,to, -1)
}

funcMap = template.FuncMap{
        "replace":  replace,
}
template := template.New("").Funcs(internalFuncMap)

and use the template to render the view.

code ref links

  1. https://github.com/sairam/kinli/blob/master/template_funcs.go#L57-L59
  2. https://github.com/sairam/kinli/blob/master/templates.go#L48
Sairam
  • 2,708
  • 1
  • 25
  • 34