Introduction
Recently, when sorting out our project code, I found that many active codes are very similar in structure and provided functions. To facilitate future development, I spent a little time writing a tool to generate code frameworks to minimize repetitive labor. The code itself is not complicated and has a high correlation with the project code, so I will not introduce it here. During this process, I found that the Go standard template libraries text/template and html/template are more confusing and inconvenient to use. I learned from GitHub that quicktemplate is a third-party template library, which is powerful, has simple syntax and is easy to use. Today we will introduce quicktemplate.
Quick use
This article's code uses Go Modules.
Create the code directory first and initialize it:
$ mkdir quicktemplate && cd quicktemplate $ go mod init /darjun/go-daily-lib/quicktemplate
quicktemplate converts the template code we wrote into Go language code. So we need to install the quicktemplate package and a compiler named qtc:
$ go get -u /valyala/quicktemplate $ go get -u /valyala/quicktemplate/qtc
First, we need to write a template file in quicktemplate format, and the template file uses .qtpl as the extension by default. Below I wrote a simple template file:
All text outside function is treated as comments. {% func Greeting(name string, count int) %} {% for i := 0; i < count; i++ %} Hello, {%s name %} {% endfor %} {% endfunc %}
The template syntax is very simple, we only need to briefly understand the following 2 points:
- Template is in units of functions, and functions can accept any type and number of parameters that can be used in functions. All text outside of the function is comment, and comments are ignored when qtc compiles;
- Except for the syntax structure, the contents in the function will be output to the rendered text as is, including spaces and line breaks.
It will be saved to the templates directory and then execute the qtc command. This command will generate the corresponding Go file, with the package name templates. Now we can use this template:
package main import ( "fmt" "/darjun/go-daily-lib/quicktemplate/get-started/templates" ) func main() { (("dj", 5)) }
Call the template function, pass in parameters, and return the rendered text:
$ go run .
Hello, djHello, dj
Hello, dj
Hello, dj
Hello, dj
{%s name %} performs text replacement, and {% for %} loops to generate duplicate text. Multiple spaces and line breaks appear in the output, because except for the syntax structure, other contents in the function will be retained as it is, including spaces and line breaks.
It should be noted that since quicktemplate converts the template to Go code for use, if the template is modified, you must first execute the qtc command to regenerate the Go code, otherwise the modification will not take effect.
Syntax Structure
quicktemplate supports common syntax structures of Go, if/for/func/import/return. Moreover, the writing method is not much different from writing Go code directly, and there is almost no learning cost. It is just that when using these syntax in templates, you need to wrap it with {% and %}, and if and for, etc. need to add endif/endfor to clearly indicate the end.
variable
Above we have seen how to render the parameter name passed in, using {%s name %}. Since name is a string type, use s to specify the type after {%. quicktemplate also supports other types of values:
- Integer: {%d int %}, {%dl int64 %}, {%dul uint64 %};
- Float: {%f float %}. You can also set the accuracy of the output, using {% float %}. For example {%f.2 1.2345 %} output 1.23;
- Byte slice ([]byte): {%z bytes %};
- String: {%q str %} or byte slice: {%qz bytes %}, quotation marks escaped to ";
- String: {%j str %} or byte slice: {%jz bytes %}, without quotes;
- URL encoding: {%u str %}, {%uz bytes %};
- {%v anything %}: The output is equivalent to ("%v", anything).
Write the template first:
{% func Types(a int, b float64, c []byte, d string) %} int: {%d a %}, float64: {%f.2 b %}, bytes: {%z c %}, string with quotes: {%q d %}, string without quotes: {%j d %}. {% endfunc %}
Then use:
func main() { ((1, 5.75, []byte{'a', 'b', 'c'}, "hello")) }
run:
$ go run .
int: 1, float64: 5.75, bytes: abc, string with quotes: "hello", string without quotes: hello.
Calling functions
quicktemplate supports calling template functions and standard library functions in templates. Since qtc will directly generate Go code, we can even write our own functions to call the template in the same directory, and the functions defined in template B can also be called in template A.
We first write a file in the templates directory, define a Rank function, pass in the score, and return the rating:
package templates func Rank(score int) string { if score >= 90 { return "A" } else if score >= 80 { return "B" } else if score >= 70 { return "C" } else if score >= 60 { return "D" } else { return "E" } }
Then we can call this function in the template:
{% import "fmt" %} {% func ScoreList(name2score map[string]int) %} {% for name, score := range name2score %} {%s ("%s: score-%d rank-%s", name, score, Rank(score)) %} {% endfor %} {% endfunc %}
Compile template:
$ qtc
Write a program:
func main() { name2score := make(map[string]int) name2score["dj"] = 85 name2score["lizi"] = 96 name2score["hjw"] = 52 ((name2score)) }
Run the program output:
$ go run .
dj: score-85 rank-B
lizi: score-96 rank-A
hjw: score-52 rank-E
Since we use the fmt package in our templates, we need to import the package first using {% import %}.
The function that calls another template in the template is similar, because the templates will eventually be converted to Go code. There are functions with the same signature in Go code.
Web
Quicktemplate is often used to write HTML page templates:
{% func Index(name string) %} <html> <head> <title>Awesome Web</title> </head> <body> <h1>Hi, {%s name %} <p>Welcome to the awesome web!!!</p> </body> </html> {% endfunc %}
Here is a simple web server:
func index(w , r *) { (w, ("name")) } func main() { mux := () ("/", index) server := &{ Handler: mux, Addr: ":8080", } (()) }
qtc will generate a Write* method, which accepts a parameter. When writing the template rendering results into this, we can pass them directly as parameters, which is very convenient.
run:
$ qtc
$ go run .
Enter localhost:8080?name=dj to view the results.
Summarize
Quicktemplate has at least the following 3 advantages:
- The grammar is very similar to Go, with almost no learning cost;
- It will be converted to Go first, and the rendering speed is very fast, more than 20 times faster than the standard library html/template;
- For security reasons, some encoding will be performed to avoid attacks.
Judging from my personal actual usage, it is indeed very convenient and practical. If you are interested, you can also check out the Go code generated by qtc.
If you find a fun and useful Go language library, welcome to submit an issue on the Go daily library GitHub
refer to
quicktemplate GitHub:/valyala/quicktemplate
Go daily library GitHub:/darjun/go-daily-lib
This is the end of this article about the use of quicktemplate in Go daily library. For more related Go quicktemplate content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!