duangu6588 2017-02-07 09:38
浏览 72
已采纳

Golang从包含的模板中访问模板变量[重复]

This question already has an answer here:

In golang, I am working with three files: index.html, nav.html and main.go

nav.html contains the following:

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

index.html contains the following:

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

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

I am using Golang's template package along with Martini which is not too important in this case.

My main.go file contains:

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()
}

My problem:

The .path variable being parsed into the index template is only accessable by the index template itself.

I include the nav template using {{ template "nav" }} inside index.html. The issue is, nav.html cannot access the .path variable. It is only accessable by the index template.

Is there any way to make the .path variable accessable to all included template files, in my case index.html and nav.html?

</div>
  • 写回答

1条回答 默认 最新

  • douhan9191 2017-02-07 09:50
    关注

    You can pass the data to the nested template as an argument like this: {{ template "nav" . }} Now the dot will be accessible within the define "nav" block.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集