GoFrame 模板引擎-其他使用

2022-04-01 16:56 更新

I18N支持

模板引擎支持?i18n?特性,可以通過給上下文注入特定的?i18n?語言來實(shí)現(xiàn)不同的請(qǐng)求/頁面使用不同的?i18n?語言渲染。例如:

package main

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/i18n/gi18n"
)

func main() {
	var (
		ctxCN   = gi18n.WithLanguage(context.TODO(), "zh-CN")
		ctxJa   = gi18n.WithLanguage(context.TODO(), "ja")
		content = `{{.name}} says "{#hello}{#world}!"`
	)

	result1, _ := g.View().ParseContent(ctxCN, content, g.Map{
		"name": "john",
	})
	fmt.Println(result1)

	result2, _ := g.View().ParseContent(ctxJa, content, g.Map{
		"name": "john",
	})
	fmt.Println(result2)
}

執(zhí)行后,輸出結(jié)果為:(保證當(dāng)前運(yùn)行目錄帶有i18n轉(zhuǎn)譯配置文件)

john says "你好世界!"
john says "こんにちは世界!"

HTTP對(duì)象視圖

?goframe?框架的?WebServer?的返回對(duì)象中提供了基礎(chǔ)的模板解析方法,如下:

func (r *Response) WriteTpl(tpl string, params map[string]interface{}, funcMap ...map[string]interface{}) error
func (r *Response) WriteTplContent(content string, params map[string]interface{}, funcMap ...map[string]interface{}) error

其中?WriteTpl?用于輸出模板文件,?WriteTplContent?用于直接解析輸出模板內(nèi)容。

使用示例:

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")
		r.Response.WriteTplContent(`Cookie:{{.Cookie.theme}}, Session:{{.Session.name}}`, nil)
	})
	s.SetPort(8199)
	s.Run()
}

執(zhí)行后,輸出結(jié)果為:

Cookie:default, Session:john

控制器視圖管理

?goframe?為路由控制器注冊(cè)方式提供了良好的模板引擎支持,由?gmvc.View?視圖對(duì)象進(jìn)行管理,提供了良好的數(shù)據(jù)隔離性。控制器視圖是并發(fā)安全設(shè)計(jì)的,允許在多線程中異步操作。

控制器注冊(cè)方式類似于PHP執(zhí)行流程,相對(duì)來說性能比較低效,因此未來不再推薦使用控制器注冊(cè)方式。

func (view *View) Assign(key string, value interface{})
func (view *View) Assigns(data gview.Params)

func (view *View) Parse(file string) ([]byte, error)
func (view *View) ParseContent(content string) ([]byte, error)

func (view *View) Display(files ...string) error
func (view *View) DisplayContent(content string) error

func (view *View) LockFunc(f func(vars map[string]interface{}))
func (view *View) RLockFunc(f func(vars map[string]interface{}))

使用示例1:

package main

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

type ControllerTemplate struct {
    gmvc.Controller
}

func (c *ControllerTemplate) Info() {
    c.View.Assign("name", "john")
    c.View.Assigns(map[string]interface{}{
        "age"   : 18,
        "score" : 100,
    })
    c.View.Display("index.tpl")
}

func main() {
    s := ghttp.GetServer()
    s.BindController("/template", new(ControllerTemplate))
    s.SetPort(8199)
    s.Run()
}

其中?index.tpl?的模板內(nèi)容如下:

<html>
    <head>
        <title>gf template engine</title>
    </head>
    <body>
        <p>Name: {{.name}}</p>
        <p>Age:  {{.age}}</p>
        <p>Score:{{.score}}</p>
    </body>
</html>

執(zhí)行后,訪問 http://127.0.0.1:8199/template/info 可以看到模板被解析并展示到頁面上。如果頁面報(bào)錯(cuò)找不到模板文件,沒有關(guān)系,因?yàn)檫@里并沒有對(duì)模板目錄做設(shè)置,默認(rèn)是當(dāng)前可行文件的執(zhí)行目錄(?Linux&Mac?下是?/tmp?目錄,Windows下是?C:\Documents and Settings\用戶名\Local Settings\Temp?)。

其中,給定的模板文件?file?參數(shù)是需要帶完整的文件名后綴,例如:?index.tpl?,?index.html?等等,模板引擎對(duì)模板文件后綴名沒有要求,用戶可完全自定義。此外,模板文件參數(shù)也支持文件的絕對(duì)路徑(完整的文件路徑)。

當(dāng)然,我們也可以直接解析模板內(nèi)容,例如:

package main

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

type ControllerTemplate struct {
    gmvc.Controller
}

func (c *ControllerTemplate) Info() {
    c.View.Assign("name", "john")
    c.View.Assigns(map[string]interface{}{
        "age"   : 18,
        "score" : 100,
    })
    c.View.DisplayContent(`
        <html>
            <head>
                <title>gf template engine</title>
            </head>
            <body>
                <p>Name: {{.name}}</p>
                <p>Age:  {{.age}}</p>
                <p>Score:{{.score}}</p>
            </body>
        </html>
    `)
}

func main() {
    s := ghttp.GetServer()
    s.BindController("/template", new(ControllerTemplate{}))
    s.SetPort(8199)
    s.Run()
}

執(zhí)行后,訪問 http://127.0.0.1:8199/template/info 可以看到解析后的內(nèi)容如下:

<html>
    <head>
        <title>gf template engine</title>
    </head>
    <body>
        <p>Name: john</p>
        <p>Age:  18</p>
        <p>Score:100</p>
    </body>
</html>


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

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)