|html 这部分代码,是请求模板引擎在输出 FieldName 的结果前把值传递给 html 格式化器,它会执行 HTML 字符转义(例如把 > 替换为 >)。这可以避免用户输入数据破坏 HTML 文档结构。
15.7.2 验证模板格式
为了确保模板定义语法是正确的,使用 Must() 函数处理 Parse 的返回结果。在下面的例子中 tOK 是正确的模板, tErr 验证时发生错误,会导致运行时 panic。
package main
import (
"text/template"
"fmt"
)
func main() {
tOk := template.New("ok")
//a valid template, so no panic with Must:
template.Must(tOk.Parse("/* and a comment */ some static text: {{ .Name }}"))
fmt.Println("The first one parsed OK.")
fmt.Println("The next one ought to fail.")
tErr := template.New("error_template")
template.Must(tErr.Parse(" some static text {{ .Name }"))
}
输出:
The first one parsed OK.
The next one ought to fail.
panic: template: error_template:1: unexpected "}" in operand
在代码中常见到这 3 个基本函数被串联使用:
var strTempl = template.Must(template.New("TName").Parse(strTemplateHTML))
在上述示例代码上实现 defer/recover 机制。
15.7.3 If-else
t := template.New("template test")
t = template.Must(t.Parse("This is just static text. \n{{\"This is pipeline data - because it is evaluated within the double braces.\"}} {{`So is this, but within reverse quotes.`}}\n"))
t.Execute(os.Stdout, nil)
输出结果为:
This is just static text.
This is pipeline data—because it is evaluated within the double braces. So is this, but within reverse quotes.
现在我们可以对管道数据的输出结果用 if-else-end 设置条件约束:如果管道是空的,类似于:
{{if ``}} Will not print. {{end}}
那么 if 条件的求值结果为 false,不会有输出内容。但如果是这样:
{{if `anything`}} Print IF part. {{else}} Print ELSE part.{{end}}
会输出 Print IF part.。以下程序演示了这点:
package main
import (
"os"
"text/template"
)
func main() {
tEmpty := template.New("template test")
tEmpty = template.Must(tEmpty.Parse("Empty pipeline if demo: {{if ``}} Will not print. {{end}}\n")) //empty pipeline following if
tEmpty.Execute(os.Stdout, nil)
tWithValue := template.New("template test")
tWithValue = template.Must(tWithValue.Parse("Non empty pipeline if demo: {{if `anything`}} Will print. {{end}}\n")) //non empty pipeline following if condition
tWithValue.Execute(os.Stdout, nil)
tIfElse := template.New("template test")
tIfElse = template.Must(tIfElse.Parse("if-else demo: {{if `anything`}} Print IF part. {{else}} Print ELSE part.{{end}}\n")) //non empty pipeline following if condition
tIfElse.Execute(os.Stdout, nil)
}
输出:
Empty pipeline if demo:
Non empty pipeline if demo: Will print.
if-else demo: Print IF part.
15.7.4 点号和 with-end
点号 (.) 可以在 Go 模板中使用:其值 {{.}} 被设置为当前管道的值。
with 语句将点号设为管道的值。如果管道是空的,那么不管 with-end 块之间有什么,都会被忽略。在被嵌套时,点号根据最近的作用域取得值。以下程序演示了这点: