亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang中定義模板內的變量

Golang中定義模板內的變量

Go
Helenr 2022-01-10 17:06:28
我在 Golang 項目中有 3 個文件,想法是在 layout.html 的正文中呈現 index.html。有用。但是當我嘗試將變量傳遞給index.html 時,console.log()沒有呈現。當我移動console.log()到layout.html 時,我可以從.html中看到 JSON 的內容.tes。這是項目文件。布局.html<!DOCTYPE html><html><head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1">    <title>{{.title}} | {{.project_name}}</title></head><body style="width:100%; height: 100%; overflow-x: visible"><div id="wrapper" style="width:100%; height:100%; margin: 0 auto">    {{template "contents"}}</div></body></html>索引.html{{define "contents"}}<script>    var x = {{.tes}};    console.log(x)</script>{{end}}路由器.gofunc init() {    // handler    http.HandleFunc("/", RenderPage)}func RenderPage(w http.ResponseWriter, r *http.Request) {    tes := map[string]interface{}{        "item":"TEST3",        "count":4567,    }    Data := map[string]interface{}{        "title":"TEST1",        "project_name":"TEST2",        "tes":M.ToJSON(tes),    }    tmpl, err := template.ParseFiles("page/layout.html", "page/index.html")    X.CheckError(err)    err = tmpl.Execute(w, Data)    X.CheckError(err)}
查看完整描述

1 回答

?
Qyouu

TA貢獻1786條經驗 獲得超11個贊

在 layout.HTML 中,您需要傳遞上下文。你用一個.點來做。

    {{ template "contents" . }}

或者,您可以傳遞您想要的任何 var 的值:

    {{ template "contents" .tes }}

...在內容模板中,點上下文將只是.tes. 這有助于限制子模板的范圍,而不必通過 dot-walk 來獲得一個值。


查看完整回答
反對 回復 2022-01-10
  • 1 回答
  • 0 關注
  • 521 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號