I have problem with displaying URL from database in my template. I have struct:
type Tag struct {
gorm.Model
URL: string
userID: uint
}
when I fetch all tags and try display it
{{range $element := .}}
{{$element.URL}}
{{end}}
I get escaped url. I see before was available | unescape but this don't exist anymore. I try also with custom function to return template.URL but still dont work.
This is my try:
"unscape" : func(s string) template.URL {
return template.URL(fmt.Sprint(s))
}
Need to tell template engine that url is safe.
To achieve it need to return template.HTML
or template.URL
.
funcMap := template.FuncMap{
"safeHTML" : template.HTML,
"safeURL" : template.URL,
}
And then try to call Your method in template expression
{{range $element := .}}
{{safeURL $element.URL}}
{{end}}
By manual for template package :
Typed Strings
By default, this package assumes that all pipelines produce a plain text string. It adds escaping pipeline stages necessary to correctly and safely embed that plain text string in the appropriate context.
When a data value is not plain text, you can make sure it is not over-escaped by marking it with its type.
Types HTML, JS, URL, and others from content.go can carry safe content that is exempted from escaping.
The template
Hello, {{.}}!
can be invoked with
tmpl.Execute(out, template.HTML(`<b>World</b>`))
to produce
Hello, <b>World</b>!
instead of the
Hello, <b>World<b>!
that would have been produced if {{.}} was a regular string.
I dont know why but I must save it in variable to it be correct I fix it like this.
"safe": func(s string) template.URL {
fixedurl := template.URL(s)
return fixedurl
},
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.