Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

go - What's the easiest way to define a custom HTML-stringification?

Is there a way for me to define that when I just output a value in Go html templates the way the formatting is done instead of it printing a string representation without having to call a function to explicitcly convert it?

For example, let's say I have a type Person and I have a template with just {{.}} I want it to automatically create a link to that person's page but if I use the same template and passed a value of a different type some other HTML will be generated.

What I don't want to do is having to write something like {{.HTML}} or {{. | html}}. I'm already aware that these are possible but my question is specifically about how to avoid those.

I've played around with the thought of Person.String() having return the HTML code somehow without it being escaped but besides not getting that to work it also seems like an ugly solution.

Another solution I've thought about is to just pass everything as HTML into the template but then I couldn't access the attributes anymore (like {{.name}} to output just the name) and I'd also have to convert everything into HTML just in case it's used in the template.

question from:https://stackoverflow.com/questions/65920132/whats-the-easiest-way-to-define-a-custom-html-stringification

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Create a method that returns an template.HTML type. i.e.:

func (p *Person) HTML() template.HTML {
    return fmt.Sprintf(`<a href="/person/%v">%s</a>`, p.id, template.HTMLEscapeString(p.name))
}

Then in your template:

{{ .HTML }}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...