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

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

更新嵌套模板 Golang

更新嵌套模板 Golang

Go
浮云間 2023-06-05 17:52:17
我正在嘗試動態更改內容。但內容保持不變。似乎要獲取第一場比賽。不管模板是什么。即使使用硬編碼文件名也不起作用。代碼按預期工作,但內容無法更改。主要布局{{define "layout"}}    <html>    <body>        {{ template "content" }}    </body>    </html>{{end}}子模板 1{{ define "content" }}<h1 style="color: red;">Page 1!</h1>{{ end }}子模板 2{{ define "content" }}<h1 style="color: blue;">Page 2!</h1>{{ end }}圍棋代碼package mainimport (    "html/template"    "net/http"    "strings")var tpl *template.Templatefunc init() {    tpl = template.Must(template.ParseGlob("templates/*.gohtml"))}func main() {    http.HandleFunc("/", index)    http.ListenAndServe(":8080", nil)}func index(w http.ResponseWriter, r *http.Request) {    path := strings.Trim(r.URL.Path, "/")    switch path {    case "":        path = ("index.gohtml")    default:        path = (path + ".gohtml")    }    err := tpl.ExecuteTemplate(w, "layout", path)    if err != nil {        http.Error(w, err.Error(), http.StatusInternalServerError)        return    }}我也曾嘗試在執行之前執行 ParseFiles,但沒有成功。我究竟做錯了什么?
查看完整描述

3 回答

?
慕運維8079593

TA貢獻1876條經驗 獲得超5個贊

我認為,在解析模板后調整路徑為時已晚。

可行的方法(雖然我不確定這里是否是最優雅的解決方案)是使用以下AddParseTree方法:

AddParseTree 為具有給定名稱的模板添加解析樹并將其與 t 相關聯。如果模板尚不存在,它將創建一個新模板。如果模板確實存在,它將被替換。

適用于您的情況,根據您將Parse相關模板文件(子模板 1 或 2)的條件,然后在執行之前將其添加到AddParseTreeto 。tpl


查看完整回答
反對 回復 2023-06-05
?
慕萊塢森

TA貢獻1810條經驗 獲得超4個贊

最后我讓它工作了,但只有在不遵循手冊的情況下。


解決方案第 1 部分


跳過模板中的 {{define}} 和 {{end}}。詭異的...


<html>

? <head>

? ? <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

? ? <title>Go Web Programming</title>

? </head>

? <body>

? ? layout level

? ? {{ template "content" . }}

? </body>

</html>

在子模板中也是如此......


<h1 style="color: red;">Page 1!</h1>

解決方案第 2 部分

我找到了一個帶有 AddParsTree 的代碼片段,這是代碼(經過簡化,沒有錯誤處理)


package main


import (

? ? "html/template"

? ? "net/http"

? ? "strings"

)


var tpl *template.Template


func init() {

? ? tpl = template.Must(template.ParseGlob("templates/*.html"))

}


func main() {

? ? http.HandleFunc("/", index)

? ? http.ListenAndServe(":8080", nil)

}


func index(w http.ResponseWriter, r *http.Request) {


? ? path := strings.Trim(r.URL.Path, "/")

? ? switch path {

? ? case "":

? ? ? ? path = ("home.html")

? ? default:

? ? ? ? path = (path + ".html")

? ? }


? ? layout := tpl.Lookup("layout.html")

? ? layout, _ = layout.Clone()

? ? t := tpl.Lookup(path)

? ? _, _ = layout.AddParseTree("content", t.Tree)

? ? layout.Execute(w, "")

我真的不明白為什么我必須不遵守手冊才能讓它工作。任何啟發我的評論將不勝感激。


查看完整回答
反對 回復 2023-06-05
?
料青山看我應如是

TA貢獻1772條經驗 獲得超8個贊

我遇到了同樣的問題并以這種方式解決了它:


這對我來說適用于{{ define "content1" }}...{{ end }}語法,但你必須給你的模板唯一的名稱:content1和content2。


我制作了一個用于處理模板內容的包。


package templates


import (

    "html/template"

    "log"

    "net/http"

)


var tmpls *template.Template


// LoadTemplates parses a template folder

func LoadTemplates(tmplPath string) {

    tmpls = template.Must(template.ParseGlob(tmplPath))

}


// ExecTmpl executes a template and writes it

func ExecTmpl(w http.ResponseWriter, tmpl string, data interface{}) {

    tmpls.ExecuteTemplate(w, tmpl, data)

}


// ExecTmplTree combines and executes two templates

func ExecTmplTree(w http.ResponseWriter, outer, inner string, data interface{}) {

    layout, err := tmpls.Lookup(outer).Clone()

    if err != nil || layout == nil {

        log.Fatal("ExecTmplTree: Could not get a copy of template", outer)

    }

    content, err := tmpls.Lookup(inner).Clone()

    if err != nil || content == nil {

        log.Fatal("ExecTmplTree: Could not get a copy of template", inner)

    }

    _, err = layout.AddParseTree("content", content.Tree)

    if err != nil {

        log.Fatal("ExecTmplTree: Templates could not be combined.")

    }

    layout.Execute(w, data)

}


然后我調用函數如下(在 main.go 或其他地方):


// call first to load templates from the folder where your templates are stored

// you might need fit the file ending, too, I simply use .html for html-templates

func init() {

    templates.LoadTemplates("web/templates/*.html")

}


// write a basic template without nesting

func exampleHandler(w http.ResponseWriter, r *http.Request) {

    templates.ExecTmplTree(w, "content1", "messageForm", nil)

}


// write nested templates. here, index is the outer template

// and code is the inner

func indexHandler(w http.ResponseWriter, r *http.Request) {

    templates.ExecTmplTree(w, "layout", "content1", nil)

}


查看完整回答
反對 回復 2023-06-05
  • 3 回答
  • 0 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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