英文:
How to replace string in Go template?
问题
我使用"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模板:
[image]
src = "{{ replace .Media.ThumbnailUrl 's72-c' 's1600' }}"
link = ""
thumblink = "{{ .Media.ThumbnailUrl }}"
alt = ""
title = ""
author = ""
license = ""
licenseLink = ""
replace
函数未定义。我想要替换{{ .Media.ThumbnailUrl }}
中的URL。
例如:
从这个URL:
https://2.bp.blogspot.com/-DEeRanrBa6s/WGWGwA2qW5I/AAAAAAAADg4/feGUc-g9rXc9B7hXpKr0ecG9UOMXU3_VQCK4B/s72-c/pemrograman%2Bjavascript%2B-%2Bpetanikode.png
到这个URL:
https://2.bp.blogspot.com/-DEeRanrBa6s/WGWGwA2qW5I/AAAAAAAADg4/feGUc-g9rXc9B7hXpKr0ecG9UOMXU3_VQCK4B/s1600/pemrograman%2Bjavascript%2B-%2Bpetanikode.png
英文:
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 <code>{{ .Media.ThumbnailUrl }}</code>
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
答案1
得分: 11
你可以编写一个辅助视图函数,像这样:
func replace(input, from, to string) string {
return strings.Replace(input, from, to, -1)
}
funcMap := template.FuncMap{
"replace": replace,
}
template := template.New("").Funcs(funcMap)
然后使用template
来渲染视图。
代码参考链接如下:
英文:
> 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论