Golang GAE – HTML模板未正确插入链接到网页中

huangapple go评论105阅读模式
英文:

Golang GAE - HTML Template not inserting links properly into web page

问题

我正在使用Google App Engine上的Google Go。我正在将一个string描述保存到一个结构体中的datastore中,如下所示:

type Foo struct{
    Bar string
}

该描述包含HTML标签,例如:

<a href="/">Bar</a>

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

<html><head><title>Title</title></head>
<body>{{.Bar}}</body></html>

解析为:

<html><head><title>Title</title></head>
<body><a href="/">Bar</a></body></html>

但是,实际上,我得到的是这样的:

<html><head><title>Title</title></head>
<body><a href="/">Bar's</a></body></html>

如何使模板正确解析string为HTML链接?

英文:

I am using Google Go on Google App Engine. I am saving a string description in a structure into a datastore, like so:

type Foo struct{
    Bar string
}

That description includes html tags, for example:

<a href="/">Bar</a>

I want the html template to include that description in an html file so it would be parsed as html. For example:

<html><head><title>Title</title></head>
<body>{{.Bar}}</body></html>

to be parsed as:

<html><head><title>Title</title></head>
<body><a href="/">Bar</a></body></html>

but instead, I get something like this:

<html><head><title>Title</title></head>
<body><a href="/">Bar's</a></body></html>

How can I make the template parse the string correctly into an html link?

答案1

得分: 5

The "http/template" package automatically escapes all strings. To get around this you must make the value of type template.HTML. E.g.

import "html/template"

type Foo struct {
    Bar template.HTML
}

And then in your code do something like:

Foo.Bar = template.HTML(barString)
英文:

The "http/template" package automatically escapes all strings. To get around this you must make the value of type template.HTML. E.g.

import "html/template"

type Foo struct {
    Bar template.HTML
}

And then in your code do something like:

Foo.Bar = template.HTML(barString)

huangapple
  • 本文由 发表于 2012年11月4日 06:25:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/13214095.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定