官术网_书友最值得收藏!

How to do it…

In this recipe, we are going to create a first-template.html with a couple of placeholders whose value will be injected by the template engine at runtime. Perform the following steps:

  1. Create first-template.html inside the templates directory by executing the following Unix command:
$ mkdir templates && cd templates && touch first-template.html
  1. Copy the following content to first-template.html:
<html>
<head>
<meta charset="utf-8">
<title>First Template</title>
<link rel="stylesheet" href="/static/stylesheets/main.css">
</head>
<body>
<h1>Hello {{.Name}}!</h1>
Your Id is {{.Id}}
</body>
</html>

The preceding template has two placeholders, {{.Name}} and {{.Id}}, whose values will be substituted or injected by the template engine at runtime.

  1. Create first-template.go, where we will populate the values for the placeholders, generate an HTML as an output, and write it to the client, as follows:
import 
(
"fmt"
"html/template"
"log"
"net/http"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
type Person struct
{
Id string
Name string
}
func renderTemplate(w http.ResponseWriter, r *http.Request)
{
person := Person{Id: "1", Name: "Foo"}
parsedTemplate, _ := template.ParseFiles("templates/
first-template.html")
err := parsedTemplate.Execute(w, person)
if err != nil
{
log.Printf("Error occurred while executing the template
or writing its output : ", err)
return
}
}
func main()
{
http.HandleFunc("/", renderTemplate)
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil)
if err != nil
{
log.Fatal("error starting http server : ", err)
return
}
}

With everything in place, the directory structure should look like the following:

  1. Run the program with the following command:
$ go run first-template.go
主站蜘蛛池模板: 泰兴市| 天镇县| 资源县| 砚山县| 汉阴县| 荔波县| 湖北省| 延寿县| 太保市| 南江县| 福鼎市| 文水县| 丘北县| 集贤县| 英德市| 肥东县| 昌黎县| 大埔县| 霍城县| 凯里市| 兴化市| 仙桃市| 吉木萨尔县| 吉木乃县| 和林格尔县| 虞城县| 广东省| 黔西| 双辽市| 托克逊县| 会昌县| 邻水| 玛纳斯县| 新巴尔虎左旗| 宜州市| 康乐县| 定日县| 武功县| 临洮县| 祁连县| 醴陵市|