2017-02-07 103 views
0

在golang,我有三個文件時:的index.html,nav.html和main.goGolang訪問模板變量從包含的模板

nav.html包含以下內容:

{{ define "nav" }} 
    <nav class="nav-container"> 
    <h1>{{ .path }}</h1> 
    </nav> 
{{ end }} 

的index.html包含以下內容:

{{ define "index" }} 
    {{ template "nav" }} <!-- Includes the nav.html file --> 

    <h1>Welcome to my website. You are visiting {{ .path }}.</h1> 
{{ end }} 

我正在使用Golang的template包以及Martini這在這種情況下並不太重要。

我main.go文件包含:

package main 

import (
    "net/http" 

    "github.com/go-martini/martini" 
    "github.com/martini-contrib/render" 
) 

func main() { 
    m := martiniSetup() 

    m.Get("/", func(res http.ResponseWriter, req *http.Request, ren render.Render, params martini.Params) { 
     parse := make(map[string]interface{}) 
     parse["path"] = req.URL.Path 

     ren.HTML(http.StatusOK, "index", parse) 
    }) 

    m.Run() 
} 

我的問題:

.path變量被解析成index模板只能由index模板本身accessable。

我在index.html的內部使用{{ template "nav" }}包含nav模板。問題是,nav.html無法訪問.path變量。它只能由索引模板訪問。

有什麼辦法可以使.path變量可以訪問所有包含的模板文件,在我的例子中是index.htmlnav.html

回答

0

您可以將數據作爲參數傳遞給嵌套模板,如下所示:​​ 現在可以在define "nav"塊內訪問該點。

+0

非常感謝!這工作! :) – Acidic