指令用于在 Go 模板中嵌入命令,通过 {
{
和 }}
来定义,Go 提供了丰富的指令集,包括条件判断、循环、设置和引入等。
在众多 Go 模板指令中,.
是最重要的一个,它用于解析传递到模板的数据,其他指令和函数大多都是围绕这个 .
进行格式化和显示。
1、条件指令
要在视图模板中使用 if 条件判断,可以这么做:
{
{ if arg }}
some content
{
{ end }}
还可以编写 if…else… 控制结构语句:
{
{ if arg }}
some content
{
{ else }}
other content
{
{ end }}
其中 arg
可以是常量、变量、或者返回某个值的函数或方法。
下面看一个简单的示例,编写服务端处理器代码如下:
package main
import (
"html/template"
"math/rand"
"net/http"
"time"
)
func process(w http.ResponseWriter, r *http.Request) {
t := template.Must(template.ParseFiles("condition.html"))
rand.Seed(time.Now().Unix())
t.Execute(w, rand.Intn(10) > 5)
}
func main() {
http.HandleFunc("/condition", process)
http.ListenAndServe(":8080", nil)
}
对应的模板代码 condition.html
:
html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Condition Actionstitle>
head>
<body>
{
{ if . }}
Number is greater than 5!
{
{ else }}
Number is less than or equal to 5!
{
{ end }}
body>
html>