Golang GAE - HTML模板没有正确地将链接插入网页

The*_*chu 4 html google-app-engine parsing templates go

我在Google App Engine上使用Google Go.我string将结构中的描述保存为a datastore,如下所示:

type Foo struct{
    Bar string
}
Run Code Online (Sandbox Code Playgroud)

该描述包括html标签,例如:

<a href="/">Bar</a>
Run Code Online (Sandbox Code Playgroud)

我希望将该html template描述包含在html文件中,以便将其解析为html.例如:

<html><head><title>Title</title></head>
<body>{{.Bar}}</body></html>
Run Code Online (Sandbox Code Playgroud)

被解析为:

<html><head><title>Title</title></head>
<body><a href="/">Bar</a></body></html>
Run Code Online (Sandbox Code Playgroud)

但相反,我得到这样的东西:

<html><head><title>Title</title></head>
<body>&lt;a href=&#34;/&#34;&gt;Bar&#39;s&lt;/a&gt;</body></html>
Run Code Online (Sandbox Code Playgroud)

如何才能正确template解析string为HTML链接?

Kyl*_*ley 5

该"http/template"软件包自动转义所有字符串.要解决这个问题,你必须使用类型的值template.HTML.例如

import "html/template"

type Foo struct {
    Bar template.HTML
}
Run Code Online (Sandbox Code Playgroud)

然后在你的代码中执行以下操作:

Foo.Bar = template.HTML(barString)
Run Code Online (Sandbox Code Playgroud)