当我们在构建丰富的web页面的时候,除了预定义好的页面可以使用模板文件来实现,还有一种情况是经常遇到的。那就是,某一部分内容,我想使用html代码来表现一下。比如一篇图文混排还有多个段落的新闻内容,甚至里面有几个字还想换个不同的颜色和字号来强调一下。
这样的情况,对应到web后台来说,一般就是富文本编辑器编辑好的内容了。
这个内容当然常常是在一条记录中独占一个字段的。
如果这个字段的内容在客端表现的时候,需要把字段的类型定义成 template.HTML
就像这样
type News struct {
NTitle string //标题
NAuthor string //作者
NPublish string //发布时间
NContent template.HTML //内容
NAttachment string //附件
NKeyword string //关键字
NTab string //标签
NClass string //分类
}
func Joeltemplate11(writer http.ResponseWriter, request *http.Request) {
var RNTitle = request.FormValue("NTitle")
var RNAuthor = request.FormValue("NAuthor")
var RNPublish = request.FormValue("NPublish")
var RNContent = request.FormValue("NContent")
var RNAttachment = request.FormValue("NAttachment")
var RNKeyword = request.FormValue("NKeyword")
var RNTab = request.FormValue("NTab")
var RNClass = request.FormValue("NClass")
myNews := News{}
myNews.NTitle = RNTitle
myNews.NAuthor = RNAuthor
myNews.NPublish = RNPublish
myNews.NContent = template.HTML(RNContent)
myNews.NAttachment = RNAttachment
myNews.NKeyword = RNKeyword
myNews.NTab = RNTab
myNews.NClass = RNClass
t, _ := template.ParseFiles("./JoelTemplate/sayHelloNews.html")
t.ExecuteTemplate(writer, "news", myNews)
}
{{define "news"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>News</title>
</head>
<body>
News
<hr>
标题:{{.NTitle}}<br>
作者:{{.NAuthor}}<br>
发布时间:{{.NPublish}}<br>
内容:{{.NContent }}<br>
附件:{{.NAttachment}}<br>
关键字:{{.NKeyword}}<br>
标签:{{.NTab}}<br>
分类:{{.NClass}}<br>
<hr>
<form action="" method="post">
<table>
<tr>
<td>标题:</td>
<td><input id="NTitle" name="NTitle" value=""></td>
</tr>
<tr>
<td>作者:</td>
<td><input id="NAuthor" name="NAuthor" value=""></td>
</tr>
<tr>
<td>发布时间:</td>
<td><input id="NPublish" name="NPublish" value=""></td>
</tr>
<tr>
<td>内容:</td>
<td><textarea id="NContent" name="NContent" rows="5" cols="80" >{{.NContent }}</textarea></td>
</tr>
<tr>
<td>附件:</td>
<td><input id="NAttachment" name="NAttachment" value=""></td>
</tr>
<tr>
<td>关键字:</td>
<td><input id="NKeyword" name="NKeyword" value=""></td>
</tr>
<tr>
<td>标签:</td>
<td><input id="NTab" name="NTab" value=""></td>
</tr>
<tr>
<td>分类:</td>
<td><input id="NClass" name="NClass" value=""></td>
</tr>
<tr>
<td></td>
<td><input id="NSubmit" type="submit" value="提交"/></td>
</tr>
</table>
</form>
</body>
</html>
{{end}}
这是一个新闻的结构,其中“内容”要展现出各种丰富的表现形式(图片、文字、音视频文件、链接等),所以它的类型被定义为 template.HTML
前端的表现就可以是这样的了
内容直接是html代码,并被直接在页面上应用了
好了,利用这个方法,你可以随意构建页面了。