第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

如何在 Go 中使用來自常量字符串變量的嵌套模板?

如何在 Go 中使用來自常量字符串變量的嵌套模板?

Go
紅顏莎娜 2021-06-19 14:01:12
我一直在嘗試在 Go 中使用嵌套模板,但是示例或幫助文檔對我沒有幫助,另外 3 個博客中的示例不是我正在尋找的(一個很接近,也許是唯一的方法,但我想制作當(dāng)然)好的,所以我的代碼是針對 App Engine 的,在這里我將對urlfetch服務(wù)器執(zhí)行一個操作,然后我想顯示一些結(jié)果,例如Response、標(biāo)題和正文。const statusTemplate = `{{define "RT"}}Status      - {{.Status}}Proto       - {{.Proto}}{{end}}{{define "HT"}}{{range $key, $val := .}}{{$key}} - {{$val}}{{end}}{{end}}{{define "BT"}}{{.}}{{end}}{{define "MT"}}<html>    <body>        <pre>-- Response --{{template "RT"}}--  Header  --{{template "HT"}}--   Body   --{{template "BT"}}        </pre>    </body></html>{{end}}{{template "MT"}}`func showStatus(w http.ResponseWriterm r *http.Request) {    /*     *  code to get:     *  resp as http.Response     *  header as a map with the header values     *  body as an string wit the contents     */    t := template.Must(template.New("status").Parse(statusTemplate)    t.ExecuteTemplate(w, "RT", resp)    t.ExecuteTemplate(w, "HT", header)    t.ExecuteTemplate(w, "BT", body)    t.Execute(w, nil)}我的代碼實際上輸出了具有正確值的 RT、HT 和 BT 模板,然后將 MT 模板輸出為空(MT 代表主模板)。那么...如何使用字符串變量中的嵌套形式,以便上述示例有效?
查看完整描述

2 回答

?
Smart貓小萌

TA貢獻(xiàn)1911條經(jīng)驗 獲得超7個贊

我認(rèn)為您嘗試使用嵌套模板的方法是錯誤的。如果你想.在嵌套模板中定義,你必須為嵌套模板的調(diào)用提供一個參數(shù),就像你對ExecuteTemplate函數(shù)所做的一樣:


{{define "RT"}}

Status      - {{.Status}}

Proto       - {{.Proto}}

{{end}}

{{define "HT"}}

{{range $key, $val := .}}

{{$key}} - {{$val}}

{{end}}

{{end}}

{{define "BT"}}

{{.}}

{{end}}

{{define "MT"}}

<html>

    <body>

        <pre>

-- Response --

{{template "RT" .Resp}}


--  Header  --

{{template "HT" .Header}}


--   Body   --

{{template "BT" .Body}}

        </pre>

    </body>

</html>

{{end}}

{{template "MT"}}

您似乎錯過的重要部分是模板不封裝狀態(tài)。當(dāng)您執(zhí)行模板時,引擎會評估給定參數(shù)的模板,然后寫出生成的文本。它不會保存參數(shù)或為將來調(diào)用而生成的任何內(nèi)容。


文檔

文檔的相關(guān)部分:


行動

這是操作列表?!皡?shù)”和“管道”是對數(shù)據(jù)的評估,詳細(xì)定義如下。


...


{{template "name"}}

  The template with the specified name is executed with nil data.


{{template "name" pipeline}}

  The template with the specified name is executed with dot set

  to the value of the pipeline.


...

我希望這可以解決問題。


查看完整回答
反對 回復(fù) 2021-06-21
  • 2 回答
  • 0 關(guān)注
  • 242 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號