Template Engine
Features of the Template Engine
- Simple, easy to use, powerful;
- Supports multiple template directory searches;
- Supports
layouttemplate design; - Supports singleton mode for template view objects;
- Natively integrated with the configuration management module, easy to use;
- Utilizes a two-level cache design at the core, offering high performance;
- Adds new template tags and numerous built-in template variables and functions;
- Supports automatic cache update mechanism upon template file modification, which is more developer-friendly;
define/templatetags support cross-template invocation (including template files under the same template path with subdirectories);includetag supports importing template files from any path;
General View Management
General view management involves using the native template engine gview module to implement template management, including template reading and display, template variable rendering, etc. You can use the method gview.Instance to obtain a view singleton object and retrieve it according to the singleton object name. You can also obtain the default singleton gview object through the object manager g.View().
Interface Documentation :
https://pkg.go.dev/github.com/gogf/gf/v2/os/gview
Brief Explanation:
gview.Getis used to obtain the corresponding singleton template engine object based on a given template directory path;gview.Newcan also create a template engine object based on the given template directory path but without singleton management;SetPath/AddPathis used to set/add the template directory path of the current template engine object, whereSetPathwill overwrite all template directory settings, andAddPathis recommended;Assign/Assignsis used to set template variables, and all templates parsed by the template engine can use these template variables;BindFuncis used to bind template functions; for detailed usage, refer to subsequent examples;Parse/ParseContentis used to parse template files/content, allowing for temporary template variables and template functions to be given during parsing;SetDelimitersis used to set the template parsing delimiters of the template engine object, defaulting to(conflicts with thevuejsfront-end framework);
warning
Note: Starting with goframe v1.16, all template parsing methods have an additional first input parameter which is the Context.
Example 1: Parsing a Template File
index.tpl
id:`.id`, name:`.name`
main.go
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
func main() {
s := g.Server()
s.BindHandler("/template", func(r *ghttp.Request) {
r.Response.WriteTpl("index.tpl", g.Map{
"id": 123,
"name": "john",
})
})
s.SetPort(8199)
s.Run()
}
After execution, visiting http://127.0.0.1:8199/template will show the parsed content as: id:123, name:john
Example 2: Parsing Template Content
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
func main() {
s := g.Server()
s.BindHandler("/template", func(r *ghttp.Request){
tplContent := `id:`.id`, name:`.name``
r.Response.WriteTplContent(tplContent, g.Map{
"id" : 123,
"name" : "john",
})
})
s.SetPort(8199)
s.Run()
}
After execution, visiting http://127.0.0.1:8199/template will show the parsed content as: id:123, name:john
Example 3: Custom Template Delimiters
In projects, we often encounter a conflict between Golang default template variable delimiters and Vue variable delimiters (both use ). We can use the SetDelimiters method to customize the global Golang template variable delimiters:
// main.go
package main
import (
"context"
"fmt"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
v := g.View()
v.SetDelimiters("${", "}")
b, err := v.Parse(
context.TODO(),
"gview_delimiters.tpl",
map[string]interface{}{
"k": "v",
})
fmt.Println(err)
fmt.Println(b)
}
``` ```
<!-- gview_delimiters.tpl -->
test.tpl content, vars: ${.}
After execution, the resulting output is:
<nil>
test.tpl content, vars: map[k:v]
Directory Configuration Method
The GoFrame framework‘s template engine supports a highly flexible multi-directory auto-search function. The SetPath can modify the template directory to a single directory address. Additionally, the AddPath method can add multiple search directories, and the template engine will prioritize the added directories according to the order they were added, performing automatic retrieval. It searches until it finds a matching file path. If no template file is found in all search directories, it returns failure.
Default Directory Configuration :
When initializing the gview view object, the following template file search directories are automatically added by default:
- The current working directory and its
templatesubdirectory: For example, if the current working directory is/home/www,/home/wwwand/home/www/templatewill be added; - The directory where the current executable is located and its
templatesubdirectory: For example, if the binary file is located in/tmp,/tmpand/tmp/templatewill be added; - The directory where the
mainsource code package is located and itstemplatesubdirectory (effective only in the source code development environment): For example, if themainpackage is located in/home/john/workspace/gf-app,/home/john/workspace/gf-appand/home/john/workspace/gf-app/templatewill be added;
Modifying the Template Directory
The view object‘s template file search directory can be modified in the following ways. The view object will only perform configuration file retrieval in the specified directory:
- (Recommended) Retrieve the global View object in singleton mode and modify it via the
SetPathmethod; - Modify command line start parameters -
gf.gview.path; - Modify specified environment variables -
GF_GVIEW_PATH;
For example, if our executable file is main, the template engine‘s template directory can be modified in the following ways on Linux:
- (Recommended) Through singleton mode
g.View().SetPath("/opt/template")
- Via command line parameters
./main --gf.gview.path=/opt/template/
-
Via environment variables
- Modify the environment variable at startup:
GF_GVIEW_PATH=/opt/config/; ./main
* Use the `genv` module to modify the environment variable:
genv.Set("GF_GVIEW_PATH", "/opt/template")
Automatic Update Detection
The template engine uses a carefully designed cache mechanism. When a template file is first read, it is cached in memory, and future reads will directly access the cache to improve execution efficiency. Additionally, the template engine provides an automatic update detection mechanism for template files. When a template file is modified externally, the template engine can promptly detect it and refresh the cache content of the template file.
