使用golang的标准库搭建网站--2.模板解析

模板的解析

既然是搭建网站,

fmt.Fprintf(w, "Hello world, this is my first page!")

这种方式肯定就不能用了,得解析模板才行。
模板解析用到的包是”html/template”,先导包,然后改写Index函数:

//先导入html/template包
import "html/template"

func Index(w http.ResponseWriter, r *http.Request) {
    //解析指定模板文件index.html
    t, _ := template.ParseFiles("index.html")
    //输出到浏览器
    t.Execute(w, nil)
}

在准备一个html文件,如下:

<HTML>
    <head>
        <title>
            这是一个测试文件
        </title>
    </head>
    <body>
        <p>
            Hello world, this is my first page!
        </p>
    </body>
</HTML>

运行一下,得到和上面一样的结果。
这里写图片描述

接着向模板中插入数据,很容易:

func Index(w http.ResponseWriter, r *http.Request) {
    //用于保存数据的map
    data := make(map[string]string)
    t, _ := template.ParseFiles("index.html")
    data["Name"] = "BCL"
    t.Execute(w, data)
}

在HTML文件中插入一个新的标签:

<p>
    Hello , {{.Name}}
</p>

这样就能正常解析模板啦
这里写图片描述
下面我们就简单的了解一下go语言的模板的语法

未完待续…….

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值