Skip to main content
Version: 2.8.x(Latest)

Related methods:

func (r *Response) WriteTpl(tpl string, params ...gview.Params) error
func (r *Response) WriteTplContent(content string, params ...gview.Params) error
func (r *Response) WriteTplDefault(params ...gview.Params) error
func (r *Response) ParseTpl(tpl string, params ...gview.Params) (string, error)
func (r *Response) ParseTplContent(content string, params ...gview.Params) (string, error)
func (r *Response) ParseTplDefault(params ...gview.Params) (string, error)

Response supports template file/content parsing for output or template file/content parsing for return. Unlike directly using a template object to parse templates, the parsing of Response supports some request-related built-in variables. Template parsing includes the following methods:

  1. WriteTpl* methods are used for template output, parsing and outputting template files, as well as directly parsing and outputting given template content.
  2. ParseTpl* methods are used for template parsing, parsing template files or template content, and returning the parsed content.
tip

When parsing a template, the component underlying will automatically obtain the Context variables of the current link from the Request object and pass them to the template engine, so developers do not need to explicitly pass Context variables to the template engine.

Built-in Variables

Config

Access configuration items of the default configuration management (config.toml) object.

Usage:

{{.Config.ConfigurationItem}}

Access the parameter value of the Cookie object of the current request.

Usage:

{{.Cookie.KeyName}}

Session

Access the parameter value of the Session object of the current request.

Usage:

{{.Session.KeyName}}

Query

Access the request parameter values in the current Query String.

Usage:

{{.Query.KeyName}}

Form

Access the parameter values of the current form request.

Usage:

{{.Form.KeyName}}

Request

Access the current request parameter values (irrespective of the parameter submission method).

Usage:

{{.Request.KeyName}}

Usage Example

package main

import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)

func main() {
s := g.Server()
s.BindHandler("/", func(r *ghttp.Request){
r.Cookie.Set("theme", "default")
r.Session.Set("name", "john")
content :=`Config:{{.Config.redis.cache}}, Cookie:{{.Cookie.theme}}, Session:{{.Session.name}}, Query:{{.Query.name}}`
r.Response.WriteTplContent(content, nil)
})
s.SetPort(8199)
s.Run()
}

The config.toml content is:

# Redis database configuration
[redis]
disk = "127.0.0.1:6379,0"
cache = "127.0.0.1:6379,1"

After execution, visit http://127.0.0.1:8199/?name=john, the output result will be:

Config:127.0.0.1:6379,1, Cookie:default, Session:john, Query:john