This is a creation in Article, where the information may have evolved or changed.
Go template use
In the go language, use the "html/template" Package for template processing, using Parse, Parsefile, execute, and other methods to load the template. Example:
Package Mainimport ("Html/template" "OS") type Actor struct {UserName string}func tpl_merger_structdata () {t: = template. New ("struct Data demo template")//Create a template T, _ = T.parse ("Hello, {{. username}}! \ n ") //Parse template file Actor: = actor{username:" Jsrush@structmap "} //Create a data object T. Execute (OS. Stdout, actor) //Executes the merger operation of the template and outputs it to the console}func Tpl_merger_mapdata () {t: = template. New ("Map data Demo template") T, _ = T.parse ("Hello, {{. username}}!\n") Actormap: = Make (map[string]string) actormap[" UserName "] =" Jsrush@actormap "T.execute (OS. Stdout, Actormap)}func main () {tpl_merger_structdata ()//Data type = Structtpl_merger_mapdata () //data type is map}
From the example above we can see that the Go Language template operation is very simple and convenient, and other languages are similar to the template processing, is to get the data first, and then render the data.
For the convenience of demonstrating and testing the code, we use code in the following format in the next example
- Use parse instead of parsefiles, because parse can test a string directly without needing additional files
- Do not use handler to write demo code, but each test is a main, easy to test
- Use
os.Stdout
instead http.ResponseWriter
because os.Stdout
the interface is implemented io.Writer
How do I insert data in a template?
The example code above shows how to parse and render the template, and then explore in more detail how to render the data. A template is applied to a Go object, how are the fields of the go object inserted into the template?
Field operations
The Go language template consists of a {{}}
field that needs to be replaced at render time, {{.}}
representing the current object, similar to this in Java or C + +.
When the current object is a struct type, the field of the object is {{.FieldName}}
read, but one thing to be aware of: This field must be exported (the first letter of the field must be in uppercase), otherwise the error will be rendered. This is because the properties of the object are subject to the access modifier rules, and the private property is not accessible outside, so an error is generated!
When the current object is a map type, the fields of the object are read by {{. FieldName }}, which does not have the above limitations.