GoFrame 數(shù)據(jù)返回-模板解析

2022-04-14 09:50 更新

相關(guān)方法:

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?支持模板文件/內(nèi)容解析輸出,或者模板文件/內(nèi)容解析返回。與直接使用模板對(duì)象解析模板功能不同的是,?Response?的解析支持一些請(qǐng)求相關(guān)的內(nèi)置變量。模板解析包含以下方法:

  1. ?WriteTpl*?方法用于模板輸出,解析并輸出模板文件,也可以直接解析并輸出給定的模板內(nèi)容。
  2. ?ParseTpl*?方法用于模板解析,解析模板文件或者模板內(nèi)容,返回解析后的內(nèi)容。

解析模板時(shí)組件底層會(huì)自動(dòng)通過(guò)?Request?對(duì)象獲取當(dāng)前鏈路的?Context?上下文變量并傳遞給模板引擎,因此開(kāi)發(fā)者不用顯示給模板引擎?zhèn)鬟f?Context?上下文變量。

內(nèi)置變量

Config

訪問(wèn)默認(rèn)的配置管理(?config.toml?)對(duì)象配置項(xiàng)。

使用方式:

{{.Config.配置項(xiàng)}}

Cookie

訪問(wèn)當(dāng)前請(qǐng)求的?Cookie?對(duì)象參數(shù)值。

使用方式:

{{.Cookie.鍵名}}

Session

訪問(wèn)當(dāng)前請(qǐng)求的?Session?對(duì)象參數(shù)值。

使用方式:

{{.Session.鍵名}}

Query

訪問(wèn)當(dāng)前?Query String?中的請(qǐng)求參數(shù)值。

使用方式:

{{.Query.鍵名}}

Form

訪問(wèn)當(dāng)前表單請(qǐng)求參數(shù)值。

使用方式:

{{.Form.鍵名}}

Request

訪問(wèn)當(dāng)前請(qǐng)求參數(shù)值(不區(qū)分參數(shù)提交方式)。

使用方式:

{{.Request.鍵名}}

使用示例

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()
}

其中,?config.toml?內(nèi)容為:

# Redis數(shù)據(jù)庫(kù)配置
[redis]
    disk  = "127.0.0.1:6379,0"
    cache = "127.0.0.1:6379,1"

執(zhí)行后,訪問(wèn) http://127.0.0.1:8199/?name=john ,輸出結(jié)果為:

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


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)