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

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

如何渲染多個模板

如何渲染多個模板

Go
慕田峪7331174 2021-06-10 14:09:51
創建了一個基本模板。隨著呈現的 first.html 又一個模板。eg. :    var tmpl = template.Must(template.ParseFiles(    "templates/base.html",    "templates/first.html",    ))但我也想添加更多的 .html 文件來渲染。有參考嗎?
查看完整描述

3 回答

?
慕的地10843

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

如果在模板文件夾中定義所有模板,則可以使用以下命令輕松解析整個目錄:


template.Must(template.ParseGlob("YOURDIRECTORY/*"))

例如:


頭文件


{{define "header"}}

     <head>

         <title>Index</title>

     </head>

{{end}}

索引.html


{{define "indexPage"}}

    <html>

    {{template "header"}}

    <body>

        <h1>Index</h1>

    </body>

    </html>

{{end}}

main.go


package main


import(

    "html/template"

)


// compile all templates and cache them

var templates = template.Must(template.ParseGlob("YOURTEMPLATEDIR/*"))


func main(){

    ...

}


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


    // you access the cached templates with the defined name, not the filename

    err := templates.ExecuteTemplate(w, "indexPage", nil)

    if err != nil {

        http.Error(w, err.Error(), http.StatusInternalServerError)

        return

    }

}

你執行你的 indexPage-Template templates.ExecuteTemplate(w, "indexPage", nil)


查看完整回答
反對 回復 2021-06-21
?
湖上湖

TA貢獻2003條經驗 獲得超2個贊

如果你想用特定文件解析多個目錄,這里有一個代碼片段:


//parse a pattern in a specific directory  

allTemplates := template.Must(template.ParseGlob("Directory/*"))


//add another directory for parsing 

allTemplates = template.Must(allTemplates.ParseGlob("Another_Directory/*.tmpl"))


//add specific file name 

allTemplates = template.Must(allTemplates.ParseFiles("path/to/file.tmpl"))



func main() {

 ...

}


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


    // access cached template by file name (in case you didn't define its name) 

    err := allTemplates.ExecuteTemplate(w, "file.tmpl", nil)

    if err != nil {

        http.Error(w, err.Error(), http.StatusInternalServerError)

        return

    }

}


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


    // access cached template by handler name 

    err := allTemplates.ExecuteTemplate(w, "handlerName", nil)

    if err != nil {

        http.Error(w, err.Error(), http.StatusInternalServerError)

        return

    }

}

快捷方式:


allTemplates := template.Must(

        template.Must(

        template.Must(

            template.ParseGlob("directory/*.tmpl")).

            ParseGlob("another_directory/*.tmpl")).

            ParseFiles("path/to/file.tmpl")),

                )

file.tmpl 可以如下所示:


<html>

This is a template file 

</html>

name.tmpl 應該看起來像這樣


{{define "handlerName" }}

<p>this is a handler</p>

{{end}}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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