Features of the Template Engine

  1. Simple, easy to use, powerful;
  2. Supports multiple template directory searches;
  3. Supports layout template design;
  4. Supports singleton mode for template view objects;
  5. Natively integrated with the configuration management module, easy to use;
  6. Utilizes a two-level cache design at the core, offering high performance;
  7. Adds new template tags and numerous built-in template variables and functions;
  8. Supports automatic cache update mechanism upon template file modification, which is more developer-friendly;
  9. define/template tags support cross-template invocation (including template files under the same template path with subdirectories);
  10. include tag 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:

  1. gview.Get is used to obtain the corresponding singleton template engine object based on a given template directory path;
  2. gview.New can also create a template engine object based on the given template directory path but without singleton management;
  3. SetPath/AddPath is used to set/add the template directory path of the current template engine object, where SetPath will overwrite all template directory settings, and AddPath is recommended;
  4. Assign/Assigns is used to set template variables, and all templates parsed by the template engine can use these template variables;
  5. BindFunc is used to bind template functions; for detailed usage, refer to subsequent examples;
  6. Parse/ParseContent is used to parse template files/content, allowing for temporary template variables and template functions to be given during parsing;
  7. SetDelimiters is used to set the template parsing delimiters of the template engine object, defaulting to {{ }} (conflicts with the vuejs front-end framework);

Template Engine - 图1warning

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

  1. id:{{.id}}, name:{{.name}}

main.go

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. func main() {
  7. s := g.Server()
  8. s.BindHandler("/template", func(r *ghttp.Request) {
  9. r.Response.WriteTpl("index.tpl", g.Map{
  10. "id": 123,
  11. "name": "john",
  12. })
  13. })
  14. s.SetPort(8199)
  15. s.Run()
  16. }

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

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. func main() {
  7. s := g.Server()
  8. s.BindHandler("/template", func(r *ghttp.Request){
  9. tplContent := `id:{{.id}}, name:{{.name}}`
  10. r.Response.WriteTplContent(tplContent, g.Map{
  11. "id" : 123,
  12. "name" : "john",
  13. })
  14. })
  15. s.SetPort(8199)
  16. s.Run()
  17. }

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:

  1. // main.go
  2. package main
  3. import (
  4. "context"
  5. "fmt"
  6. "github.com/gogf/gf/v2/frame/g"
  7. )
  8. func main() {
  9. v := g.View()
  10. v.SetDelimiters("${", "}")
  11. b, err := v.Parse(
  12. context.TODO(),
  13. "gview_delimiters.tpl",
  14. map[string]interface{}{
  15. "k": "v",
  16. })
  17. fmt.Println(err)
  18. fmt.Println(b)
  19. }
  1. <!-- gview_delimiters.tpl -->
  2. test.tpl content, vars: ${.}

After execution, the resulting output is:

  1. <nil>
  2. 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:

  1. The current working directory and its template subdirectory: For example, if the current working directory is /home/www, /home/www and /home/www/template will be added;
  2. The directory where the current executable is located and its template subdirectory: For example, if the binary file is located in /tmp, /tmp and /tmp/template will be added;
  3. The directory where the main source code package is located and its template subdirectory (effective only in the source code development environment): For example, if the main package is located in /home/john/workspace/gf-app, /home/john/workspace/gf-app and /home/john/workspace/gf-app/template will 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:

  1. (Recommended) Retrieve the global View object in singleton mode and modify it via the SetPath method;
  2. Modify command line start parameters - gf.gview.path;
  3. 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:

  1. (Recommended) Through singleton mode
  1. g.View().SetPath("/opt/template")
  1. Via command line parameters
  1. ./main --gf.gview.path=/opt/template/
  1. Via environment variables

    • Modify the environment variable at startup:

      1. GF_GVIEW_PATH=/opt/config/; ./main
    • Use the genv module to modify the environment variable:

      1. 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.

Documentation

📄️ Template Engine - ConfigurationThe view component of the GoFrame framework is one of its cores, supporting convenient configuration management. This article provides a detailed introduction on managing view components through configuration files, including the definitions and examples of configuration items. It also explains how to use the SetConfigWithMap method for specific configuration settings to ensure proper template parsing.

📄️ Template Engine - TagsThe basic usage of template engines and template tags in the GoFrame framework, including how to customize template delimiters, use pipelines to pass data in templates, usage of conditional statements if…else, range to iterate types like slice, map, using define to define template blocks, template tag combined with define for template nesting and reuse, and the difference in usage of the include tag in the GoFrame framework.

📄️ Template Engine - VariablesHow to use custom objects as template variables in the template engine, and access object properties and call methods within the template. This is explained in detail through examples, illustrating how to implement template content parsing in the GoFrame framework, as well as the differences between using object pointers and object variables, and the rules for method calls, helping developers better master the templating technology in the GoFrame framework.

📄️ Template Engine - LayoutThe layout template layout method of the gview template engine in the GoFrame framework. gview supports two layout methods: content block management through define and template tags, and template embedding through include tags. Both methods support the transfer of template variables. The sample code demonstrates how to use these template engine techniques in the GoFrame framework.

📄️ Template Engine - XSSXSS handling when using the GoFrame framework’s template engine. By default, output variables are not HTML encoded, which may lead to XSS vulnerabilities. However, the GoFrame framework provides flexible configuration options to control encoding effects through the AutoEncode or SetAutoEncode methods to enhance output security.

📄️ Template Engine - OthersUsing different features of the template engine in the GoFrame framework, including support for I18N features and implementation in Http objects and controllers. Through example code, we demonstrate template parsing syntax and data isolation management in multi-threaded environments. Also includes usage notes on non-recommended controller registration methods.

🗃️ Template Engine - Funcs3 items