Golang
玩一下html template
如果golang要使用作为网站的话,不太可能都只靠print来处理事情,所以其实如果需要HTML档案的话,是也可以使用Temaple这个套件来辅助完成。(所以我们需要在import 引用"html/template"这个套件。
下面是一个很简单的范例,当然不可能仅是这样而已!
我们需要在自己的程序执行区域,建立一个资料夹,我自己是建立一个view的资料夹,然後建立一个档案index.html,里面大概大概写个html code
如
index.html
<div>hello gogo</div>
然後go的档案如下,之後一样要执行档案唷!
package main
import (
"html/template"
"net/http"
)
func tmpl(w http.ResponseWriter, r *http.Request) {
t1, err := template.ParseFiles("view/index.html")
if err != nil {
panic(err)
}
t1.Execute(w, "hello world")
}
func main() {
http.HandleFunc("/", tmpl)
http.ListenAndServe(":8000", nil)
}
这样执行起来,就会发现输入localhost:8000就有看到我们的index.html了。
那如果要传变数的话呢 该如何处理?
此时我们需要在html中变化成这样,目前看起来是把title 作为一个变数并且等待接值
<div>hello, gogo</div>
<h1>{{ .Title }}</h1>
Golang的程序码
package main
import (
"html/template"
"net/http"
)
func tmpl(w http.ResponseWriter, r *http.Request) {
t1, err := template.ParseFiles("view/index.html")
if err != nil {
panic(err)
}
t1.Execute(w, struct {
Title string
}{
"My Title is gogo",
})
}
func main() {
http.HandleFunc("/", tmpl)
http.ListenAndServe(":8000", nil)
}
执行看看罗!!!
这样初步就可以run起来一个简单的golang搭配html template的方式,但其实这样的模式真的只会在练习或者自用的情境下才可能真的如此应用,所以还是得找一下golang的MVC框架来玩看看罗!!!
>>: Day12:内建的 suspend 函式,好函式不用吗?(1)
前言 这一题200. Number of Islands也是top 100 liked的题目之一,是...
Structure 假设我们有两个 function 如下: func myFunctionA ()...
Iteration forEach()、every()、some() 三者的差异在於:他们会对我们...
参加这铁人赛的用意就是为了这个开发版STM32F746, 有开发版可以拿,这麽好康的事情,怎麽可以不...
=x= 🌵 建立 Dealer Manager - Content Page 後台页面 - 国家功能...