Go language template syntax
Article directory
The symbols connecting the front and back ends:{
{}}
-
The template syntax is included in
{ {}}
it, among which{ {.}}
represents.
the current object. When passing in a structure object, you can access"."
the corresponding fields of the structure. If it is composite type data, you can{ {.FiledName}}
access its fields byFiledName
Refers to the structure variable name in the corresponding go code -
Pseudocode example:
//在html文档中 <body> <p>Hello { { .Name}}</p> <p>Gender { { .Gemder}}</p> <p>Age { { .Age}}</p> </body> //在Go代码中 type UserInfo struct{ Name string Gender string Age int } user := &UserInfo{ Name:"李四", Gender: "未知", Age: 24, }
-
In this way, the back-end data is transmitted to the front-end display
note
- grammar:
{ {/*注释内容*/}}
- Function: Consistent with comments in other languages, the purpose is to improve the readability of the code
- Note: Multi-line comments can be made, but nested comments are not allowed, and must start and end close to the delimiter
pipeline
- introduce:A pipeline is an operation that produces data, such as "{ {.}}", "{ {.Name}}", etc., the Go language template grammar supports the use of the pipeline symbol "|" to link multiple instructions, and the usage is similar to the pipeline under UNIX, so the pipeline is like It's a concept, just know it
variable
- Introduction: In Action, a variable can be initialized to capture the execution result of the pipeline
- Action: In web development, Action usually refers to a handler or function that handles HTTP requests. When a user performs an operation on a web page (such as clicking a button, submitting a form), the corresponding Action will be called to process the request and perform corresponding logical operations.
- grammar:
$variable := pipeline
- Features: Actions that declare variables will not produce any output, roughly meaningWhen the variable is only declared without assigning or using it, the output of the program will not display the value of the variable or other information. Only when a variable is assigned a value and used in the program can it be seen in the output.
conditional judgment
- grammar:
{ {if pipeline}} T1 { {end}}
{ {if pipeline}} T1 { {else}} T0 { {end}}
{ {if pipeline}} T1 { {else if pipeline}} T0 { {end}}
range keyword
- To use the range keyword in Go, the value of pipeline must be an array, slice, dictionary or channel.
- grammar:
{ {range pipeline}} T1 { {end}}
{ {range pipeline}} T1 { {else}} T0 { {end}}
with keyword
- The with keyword is somewhat similar to the if keyword, the "{ {with}}" operation only conditionally executes its body when the passed pipeline is not empty
- grammar:
{ {with pipeline}} T1 { {end}}
{ {with pipeline}} T1 { {else}} T0 { {end}}
comparison function
symbol | effect |
---|---|
eq |
== |
ne |
!= |
lt |
< |
le |
<= |
gt |
> |
ge |
>= |
- Features: Only
eq
symbols can receive multiple parameters, it will compare the first parameter with the rest of the parameters at once - example:
{ {eq arg1 arg2 arg3}} ==> arg1== arg2||arg1 == arg3
custom function
-
There are predefined functions (officially defined) and custom functions (defined by yourself) in nested templates. Custom functions make templates more flexible.
-
Custom functions
Funcs()
are implemented by calling methodsFuncs()
Method definition:func (t *Template) Funcs(funcMap FuncMap) *Template
FuncMapd
definition:type FuncMap map[string]interface{}
-
Definition steps:
-
1. First define a function in the backend code: (Anonymous function as an example)
-
hello := func() (string){ return "Hello!" }
-
-
2. Call
Funcs()
method-
Note: To call
Funcs()
a method, it needs to be called before parsing the template, that is,Parse()
before the method -
bytes,err := ioutil.ReadFile("文件名/文件路径") templl,err := template.New("为模板命名(尽量和文件名字一致)").Funcs(template.FuncMap{ "hello":hello}).Parse(string(bytes))
-
-
- Call the function in the template:
{ {hello}}
- Here
hello
is specifiedFuncMap
,key
that is, the above"hello"
-
nested templates
-
Introduction: Nested templates, that is, using multiple templates in an html file, the nested template can be a separate
html
file, anddefine
a template can also be defined under the template by using keywordsdefine
Syntax: { {define "name"}} T(content) { {end}}
-
template
Execute templates by keyword- grammar:
{ {template "name"}}
{ {template "name" pipeline}}
- grammar:
-
Example: (template code)
Demo.html
-
<html> <body> <h1>{ {template "title.html"}}</h1> <div> { {template "content.html"}} </div> </body> </html> { {/*define 的定义写在html标签之下*/}} { {define "content.html"}} <li>小明</li> <li>小红</li> { {end}}
-
title.html
file definition-
<ul> <il>你好</il> </ul>
-
-
-
Backend code (main):
-
tmpl,err :=template.ParseFiles("Demo.html路径","title.html路径")
-
When parsing the code, you need to write files containing other templates inThe first one, and the rest can be in random order
-
-
Related similar code:
-
hello.html file
-
<p>大家好,我是小黑子</p>
-
-
Server.html file
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>嵌套模板</title> </head> <body> { {/*自定义函数加模板嵌套*/}} <h1>{ {Hello}}</h1> <hr> <h2>{ {template "hello.html"}}</h2> <p>{ {.}}真帅!</p> <hr> { {template "come.html"}} </body> </html> { {define "come.html"}} <ul> <li>唱</li> <li>跳</li> <li>rap</li> <li>篮球</li> </ul> { {end}}
-
-
Backend code:
-
package main import ( "html/template" "log" "net/http" ) func main() { http.HandleFunc("/", hello) http.ListenAndServe(":9000", nil) } func hello(w http.ResponseWriter, r *http.Request) { //定义模板 //解析模板,自定义函数 Hello := func() string { return "--- 欢迎来到我的舞台 ---" } tmpl, err := template.New("Sever.html").Funcs(template.FuncMap{ "Hello": Hello}).ParseFiles( "src\\使用html和template包\\Go语言模板语法\\嵌套模板\\Sever.html", "src\\使用html和template包\\Go语言模板语法\\嵌套模板\\hello.html") if err != nil { log.Println("解析模板失败!") return } name := "贤哥" //渲染模板 err = tmpl.Execute(w, name) if err != nil { log.Println("渲染模板失败!:", err) } }
-
-
This includes the use of custom functions, nested templates, and passing values
-
template inheritance
-
Introduction: Template inheritance refers to the reuse of various similar fixed sections. For example, when we develop websites, many places in different web pages are similar, so template inheritance can be used to reuse templates. Reduce the workload and the code is more concise
-
keywords
block
- grammar:
{ {block "name" pipeline}} T { {end}}
- grammar:
-
For templates that need to be inherited, you need to inherit the root template first, and then use the define keyword to define the content
-
example
-
base.tmp
document<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>模板继承</title> </head> <style> *{ background-color:white; } </style> <body> <h1 style="color:red">模板继承</h1> <hr> <h2 style="color:blue">变化的内容:</h2> <div>{ {block "context" .}} <p>会发生变化的地方</p> <div> <a href="http://localhost:9000/index">Index页面</a><br> <a href="http://localhost:9000/home">Home页面</a> </div> { {end}}</div> </body> </html>
- It involves a little bit of
css
content and does not affect reading
- It involves a little bit of
-
index.tmpl
document{ {/*继承根模板*/}} { {template "base.tmpl" .}} { {/*定义块模板*/}} { {define "context"}} <h2>Index页面</h2> <p>Hello,{ {.}}</p> <a href="http://localhost:9000">Base页面</a> { {end}}
- First inherit and then define the content, where
{ {template "base.tmpl" .}}
"." refers to the value passed in, and<p>Hello,{ {.}}</p>
"." receives the value - Also, the file name after the define here must be consistent with the name defined in the block
- First inherit and then define the content, where
-
home.tmpl
document{ {/*继承根模板*/}} { {template "base.tmpl" .}} { {/*定义块模板*/}} { {define "context"}} <h2>Home页面</h2> <p>Hello,{ {.}}</p> <a href="http://localhost:9000">Base页面</a> { {end}}
- Basically the same as above
-
backend code
package main import ( "html/template" "log" "net/http" ) func main() { http.HandleFunc("/", base) http.HandleFunc("/index", index) http.HandleFunc("/home", home) err := http.ListenAndServe(":9000", nil) if err != nil { log.Println(err) return } } func base(w http.ResponseWriter, r *http.Request) { //定义模板 //解析模板 t, err := template.New("base.tmpl").ParseFiles("src\\使用html和template包\\Go语言模板语法\\模板继承\\base.tmpl") if err != nil { log.Println("解析失败:", err) return } //渲染模板 err = t.Execute(w, nil) if err != nil { log.Println("渲染失败:", err) return } } func index(w http.ResponseWriter, r *http.Request) { //定义模板 //解析模板(涉及嵌套模板) t, err := template.New("base.tmpl").ParseFiles("src\\使用html和template包\\Go语言模板语法\\模板继承\\base.tmpl", "src\\使用html和template包\\Go语言模板语法\\模板继承\\index.tmpl") if err != nil { log.Println("解析失败:", err) return } name := "贤哥!" //渲染模板 err = t.ExecuteTemplate(w, "index.tmpl", name) if err != nil { log.Println("渲染失败:", err) return } } func home(w http.ResponseWriter, r *http.Request) { //定义模板 //解析模板 t, err := template.New("base.tmpl").ParseFiles("src\\使用html和template包\\Go语言模板语法\\模板继承\\base.tmpl", "src\\使用html和template包\\Go语言模板语法\\模板继承\\home.tmpl") if err != nil { log.Println("解析失败:", err) return } name := "振哥!" //渲染模板 err = t.ExecuteTemplate(w, "home.tmpl", name) if err != nil { log.Println("渲染失败:", err) return } }
-