修改默认标识符
go 默认的标识是以{{
开始,以}}
结束,可以使用以下方法更换
template.New("test").Delims("{[","]}").ParseFiles("file.gohtml")
当前对象
{{ . }}
中的点表示当前对象
<form action="{{ .URL }}" method="post">
注释
{{
和/*
之间不能有空格
{{/* 这是注释 */}}
声明变量
{{ $id := .ID }}
移除空格
{{-
语法去除模板内容左侧的所有空白符号, 使用-}}
去除模板内容右侧的所有空白符号{{
和-
之间不能有空格,和值之前必须要空格
{{- .Title -}}
条件判断
{{if .Id == 0 }} id 是0 {{end}}
{{if .Id == 0 }} id 是0 {{else}} id 不是0 {{end}}
{{if .Id == 0 }} id 是0 {{else if id == 1 }} id是1 {{end}}
函数
type Article struct {
Title, Body string
ID int64
}
func (a Article) Test() string {
return a.Title
}
// 调用函数
<div>{{ .Test }}</div>
// 如果函数要传参
<div>{{ .Test "参数1" "参数2" }}</div>
模板
定义模板 define
{{define "sidebar"}}
<div class="col-md-3 blog-sidebar">
<div class="p-4 mb-3 bg-white rounded shadow-sm">
<h1><a href="/" class="link-dark text-decoration-none">GoBlog</a></h1>
<p class="mb-0">摒弃世俗浮躁,追求技术精湛</p>
</div>
</div>
{{end}}
使用模板 template
{{template "sidebar" .}}