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

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

嵌套 golang 模板中的變量

嵌套 golang 模板中的變量

Go
白衣非少年 2022-03-07 16:07:35
我想在 golang 模板中定義變量,而不是在二進(jìn)制文件中,這樣就不需要重新編譯。在 Go 中,我設(shè)置了一些變量:var animals = map[string]string{    "spirit_animal":    "cat",    "spirit_predator":  "dog",}我用這個(gè)執(zhí)行模板:t.ExecuteTemplate(w, "main", variables)它將這些變量傳遞給模板?,F(xiàn)在我想把這些變量從 go 帶入“主”模板。{{$spirit_animal:="cat"}} {{$spirit_animal}}我這樣稱呼子模板:{{ template "navbar" . }}問(wèn)題是嵌套模板(子模板)似乎無(wú)法訪問(wèn)任何變量。從文檔中,“模板調(diào)用不會(huì)從其調(diào)用點(diǎn)繼承變量?!?閱讀“文本/模板”的文檔,聽(tīng)起來(lái)變量可能無(wú)法在嵌套模板中使用。關(guān)于如何將這些變量從二進(jìn)制文件中取出并放入嵌套模板可訪問(wèn)的單個(gè)文本位置的任何建議,這些模板不需要在更改時(shí)重新編譯?
查看完整描述

1 回答

?
MMMHUHU

TA貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊

你確實(shí)可以!您只需將變量傳遞到嵌套模板中。


您引用的文檔是關(guān)于模板如何無(wú)法從 go 過(guò)程中讀取變量的,除非您明確將它們傳入。


同樣,嵌套模板將獲取您傳遞給它們的任何內(nèi)容,僅此而已。


來(lái)自https://golang.org/pkg/text/template/#hdr-Actions


{{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.

下面是一個(gè)根據(jù)您的提示輕而易舉的簡(jiǎn)單示例:


package main


import (

    "os"

    "text/template"

)


func main() {

    var animals = map[string]string{

        "spirit_animal":   "cat",

        "spirit_predator": "dog",

    }


    const letter = `

{{define "echo"}}Inside a template, I echo what you say: {{.}}{{end}}

{{define "predator"}}Inside a template, I know that your predator is: {{.spirit_predator}}{{end}}


Your spirit animal is: {{.spirit_animal}}


{{template "predator" . }}


{{template "echo" .spirit_animal }}`


    t := template.Must(template.New("letter").Parse(letter))

    _ = t.Execute(os.Stdout, animals)

}

https://play.golang.org/p/3X7IQasWlsR


查看完整回答
反對(duì) 回復(fù) 2022-03-07
  • 1 回答
  • 0 關(guān)注
  • 314 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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