Golang从包含的模板访问模板变量

时间:2017-02-07 09:38:16

标签: go go-templates

在golang中,我正在使用三个文件: index.html,nav.html和main.go

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模板本身访问。

我在nav内使用{{ template "nav" }}添加了index.html模板。问题是,nav.html无法访问.path变量。它只能由索引模板访问。

有没有办法让.path变量可以访问所有包含的模板文件,在我的情况下index.htmlnav.html

1 个答案:

答案 0 :(得分:2)

您可以将数据作为参数传递给嵌套模板,如下所示:dt[, .SD := lapply(.SD, function(x) paste0('"', x, '"')), .SDcols=A:B] 现在可以在{{ template "nav" . }}块中访问该点。

相关问题