美文网首页深入浅出golang我的专题Golang 开发者
57. 用模板实现网页展示(template包)

57. 用模板实现网页展示(template包)

作者: 厚土火焱 | 来源:发表于2017-09-27 19:32 被阅读137次

用 go 实现网站开发,必须学习模板的使用。这样在网站开发完毕后,如果没有数据调用或业务逻辑的变化,只是变动界面布局显示就很轻松了。
首先我们再来实现一下简单的 web 动态站点

/**
* MyWebserver03
* @Author:  Jian Junbo
* @Email:   junbojian@qq.com
* @Create:  2017/9/27 10:21
* Copyright (c) 2017 Jian Junbo All rights reserved.
*
* Description:  内容展示 web 方式
*/
package main

import (
    "time"
    "net/http"
    "fmt"
)
func main() {
    http.HandleFunc("/", Index)
    http.ListenAndServe(":9090", nil)
}
func Index(w http.ResponseWriter, r *http.Request) {
    fmt.Printf("访问了地址 %s\n", r.URL.Path)
    fmt.Fprintf(w,"你访问了地址, %s", r.URL.Path)
}

这个站点实现了在页面上打印你当前访问的站点相对地址。


一个常见的功能,点击一个页面链接,到达一个填写表单的页面。填写完表单,提交给服务器。服务器接收表单信息。
页面链接可以这样写

fmt.Fprintf(w, "你可以在<a href='/edit'>这里编辑信息</a>")

我们把它加在 Index 函数中。这样当访问根路径的时候,就可以点击这个链接了。这个链接是让页面跳转到 edit 路径。

func Index(w http.ResponseWriter, r *http.Request) {
    fmt.Printf("%d (%s)访问了地址 %s\n", time.Now().Unix(), time.Now().Format("2006-01-02 15:04:05.0000000"), r.URL.Path)
    fmt.Fprintf(w,"<div>你访问了地址, %s</div>", r.URL.Path)
    fmt.Fprintf(w, "你可以在<a href='/edit'>这里编辑信息</a>")
}

由于在 Index 函数中,两句 Fprintf 的内容是唯一打印在页面里的。这时候页面没有完整的 HTML 编码。为了避免浏览器把这些输出当作纯字符串给输出出去,我们在第一个 fmt.Fprintf 的内容里也加上了 html 代码。这只是为了让浏览器识别为页面。如果正是点做的话,应该写出完整的页面结构代码。
这些代码运行会显示成这样

有链接的页面

完整演示常见功能,我们需要在 main 函数中增加两个对应的路径 edit 和 save

    http.HandleFunc("/edit/", editHandler)
    http.HandleFunc("/save/", saveHandler)

对应的也需要完成 editHandler 和 saveHandler 函数,以便访问对应的路径有各自相关的功能实现。
editHandler 实现了一个模板页的渲染,展现为一个表单。同时,预设了一个 Article 类型,并且把相关的数据由模板配合展示在表单下方。

type Article struct {
    Title   string              //标题
    Content string              //内容
    Author  string              //作者
    Tab     []string            //标签
    PublishTime string          //发表时间
    ViewNum int                 //浏览量
}
func editHandler(w http.ResponseWriter, r *http.Request) {
    article := Article{Title:"我的标题", Content:"这是文章的内容", Author:"厚土", Tab:[]string{"练习","实践"}, PublishTime:time.Now().Format("2006-01-02 15:04:05"), ViewNum:25}
    t, err := template.ParseFiles("tmpl/edit.html")
    if err != nil{
        fmt.Println(err)
        fmt.Fprintf(w, "页面没有准备好,请稍后再访问 ...")
        return
    }
    t.Execute(w, article)
}

这里的模板页是 edit.html 保存在 tmpl 路径下。


源码路径

如果没有找到这个模板,就会提示用户页面出错了。

页面模板出错提示

在模板页中,需要显示数据的地方,都使用 {{}} 来做了标记。{{.}}表示当前的对象,如果要访问当前对象的字段通过{{.FieldName}},但是需要注意一点:这个字段必须是导出的(字段首字母必须是大写的),否则在渲染的时候就会报错。这些标记的数据来源就是 t.Execute(w, article) 里的 article。而 form 标签中的 action 表示这个表单的数据要提交到 save 路径,method 方法是确定了提交数据的方式是 post 。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>{{.Title}}</h1>
<form action="/save/" method="post">
    <div>标题<input type="text" name="title"></div>
    <div>作者<input type="text" name="author"></div>
    <div>内容<textarea name="content" rows="20" cols="80"> {{.Content}} </textarea></div>
    <div><input type="submit" value="Save"></div>
</form>
<ul>
    <li>标题:{{.Title}}</li>
    <li>内容:{{.Content}}</li>
    <li>作者:{{.Author}}</li>
    <li>发布时间:{{.PublishTime}}</li>
    <li>标签:{{range .Tab}}{{.}}、{{end}}</li>
    <li>浏览量:{{.ViewNum}}</li>
</ul>
</body>
</html>

在 save 函数中,使用 r.FormValue 接收提交来的数据。

func saveHandler(w http.ResponseWriter, r *http.Request) {
    title := r.FormValue("title")
    author := r.FormValue("author")
    content := r.FormValue("content")

    var article Article
    article.Title = title
    article.Author = author
    article.Content = content
    article.PublishTime = time.Now().Format("2006-01-02 15:04:05.0000000")
    article.Tab = []string{""}
    article.ViewNum = 0

    fmt.Fprintf(w, "我接到了 %s\n", article.Title)
    fmt.Fprintf(w, "标题:%s\n", article.Title)
    fmt.Fprintf(w, "作者:%s\n", article.Author)
    fmt.Fprintf(w, "内容:%s\n", article.Content)
    fmt.Fprintf(w, "发布时间:%s\n", article.PublishTime)
    fmt.Fprintf(w, "标签:%s\n", article.Tab)
    fmt.Fprintf(w, "浏览:%d\n", article.ViewNum)
}

当 save 函数接收到数据后,一般的应用会保存到数据库中。本程序是把它们都显示在页面上了。

表单填写 接收提交数据

相关文章

网友评论

本文标题:57. 用模板实现网页展示(template包)

本文链接:https://www.haomeiwen.com/subject/dlayextx.html