如何在Go模板中替换字符串?

时间:2017-01-14 07:33:48

标签: go go-templates

我使用"text/template"模块。

我有像这样的结构来解析Blogger中的XML

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
}

然后我像这样创建Go Template

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

未定义替换功能。我想替换{{ .Media.ThumbnailUrl }}

中的网址

例如:

来自此网址

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

到此网址

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

1 个答案:

答案 0 :(得分:3)

  

您可以编写像这样的辅助视图功能

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

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

并使用template呈现视图。

  

代码引用链接

  1. https://github.com/sairam/kinli/blob/master/template_funcs.go#L57-L59
  2. https://github.com/sairam/kinli/blob/master/templates.go#L48