Go學習-Tpl模板的使用

Go代碼示範:html

c.Data["Website"] = "beego.me"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "index.tpl"

	c.Data["TrueCond"]=true
	c.Data["FalseCond"]=false

	type u struct {
		Name string
		Age int
		Sex string
	}
	c.Data["user"]= &u{Name:"aaa",Age:1,Sex:"boy"}

	nums:=[]int{1,2,3,4,5,6,7,8,9}
	c.Data["Nums"]=nums

	c.Data["TplVar"]="hey guys"

	c.Data["html"]="<div>hello world!</div>"

	c.Data["Pipe"]="<div>hello world!</div>"

tpl模板示範:this

<div>
    {{if .TrueCond}} //判斷
        true condition.
    {{end}}
</div>
<div>
    {{if .FalseCond}}
    {{else}}
        false condition.
    {{end}}
</div>

<div>
    {{with .user}}
    {{.Name}}<br>
    {{.Age}}<br>
    {{.Sex}}
    {{end}}
    {{range .Nums}} //循環
        {{.}}<br>
    {{end}}
</div>
<div>
    {{$tplVar := .TplVar}}  //臨時變量
    {{$tplVar}}

</div>
<div>
    {{str2html .html}} //將文本string轉換爲html
    <div>
        {{.Pipe | htmlquote}} //轉回html編碼
    </div>
</div>

<div>
{{template "test"}} //調用
</div>
{{define "test"}} //模板的嵌套,定義test
    <div>
        this is test template.
    </div>
{{end}}
相關文章
相關標籤/搜索