我有 1 個(gè)文件(原始文件)的模板,它按預(yù)期工作,現(xiàn)在當(dāng)它變大時(shí),我開始將它劃分為3 files并將數(shù)據(jù)從原始文件復(fù)制并粘貼到 3 個(gè)文件,我能夠看到模板已成功執(zhí)行,但start模板中缺少數(shù)據(jù)end,只是main模板從中正確接收數(shù)據(jù)structData例如startTemple.txt{{define "start"}}...{{end}}main.txt (here i include both template){{template "start"}}...{{template "end"}}endTemplate.txt{{define "end"}}...{{end}}我使用以下t, err := template.New(mainTemplateName).Funcs(funcMap).ParseFiles(startPath, mainPath, endPath)err = t.Execute(templFile, structData)if err != nil { logs.Logger.Error(err)}我像以前一樣使用確切的代碼,問題是來自的數(shù)據(jù)structData沒有出現(xiàn)在start生成end后的模板中,只是在main正確獲取 structData 時(shí),我在這里可能會(huì)遺漏什么?使用硬編碼數(shù)據(jù)成功生成了模板(開始主端),但是應(yīng)該來自的數(shù)據(jù)在生成期間沒有添加到模板中structDatastartend我應(yīng)該以某種方式將structDataalso添加到startandend嗎?
1 回答

一只名叫tom的貓
TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊
當(dāng)您用于template
調(diào)用另一個(gè)模板時(shí),dot
默認(rèn)情況下未設(shè)置,但您可以將值作為(可選的)第二個(gè)參數(shù)傳遞給template
這樣的:
{{template?"name"??pipeline}}
在您的情況下,您的main.txt
模板應(yīng)該是
{{template?"start"?.}} ... {{template?"end"?.}}
dot
將down的值傳遞給start
andend
模板。
因?yàn)榭梢酝ㄟ^這種方式設(shè)置 的值dot
,所以還可以以更復(fù)雜的方式將模板拆分為多個(gè)文件。例如,你可以有一個(gè) HTML 模板以卡片式的方式顯示用戶信息,無論你想在輸出中的什么地方插入這張卡片,你都可以調(diào)用模板并將它傳遞給用戶,即使周圍的模板也需要其他信息或在循環(huán)中。
- 1 回答
- 0 關(guān)注
- 132 瀏覽
添加回答
舉報(bào)
0/150
提交
取消