Use template engine, hope it will be helpful to friends in need!
1 OverviewWhen processing the response body, the most common way is to send the processed HTML code. Since the data needs to be Embedded into HTML, then a template engine is the best choice.
In the Go language, the html/template
package is provided to implement the related functions of the template engine. Quick usage example:
The above code completes the basic use of the template engine, including parsing templates, rendering data, and responding to result operations. Details follow.
2 Parse templateFunctiontemplate.ParseFiles(filenames ...string) (*Template, error)### You can parse template files and get template objects . The parameter is the template file. At the same time, the file name of the template file (excluding the suffix) will be used as the name of the template. ######You can also use ###template.New("name").Parse(src string)### to create a template object and complete the parsing of the template content. ######3 Apply data and send response######Function###func (t *Template) Execute(wr io.Writer, data interface{}) error### Apply data to parsed on the template and write the output to wr. If an error occurs during execution, execution will stop, but some data of wr may have been written. ######data can accept any type. The most common type is: ###map[string]interface{}###. Different subscripts are used to distinguish part of the allocated data. Use ###.User###, ###.List### in the template to access User and List in the distribution data. ######over! ######
The above is the detailed content of How to use template engine in Go language. For more information, please follow other related articles on the PHP Chinese website!
Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete