douhe2305 2013-06-24 20:11
浏览 63
已采纳

在Go模板中,访问范围内的父/全局管道

Is it possible, within a {{range pipeline}} T1 {{end}} action in the text/template package to access the pipelines value prior to the range action, or the parent/global pipeline passed as an argument to Execute?

Working example that shows what I try to do:

package main

import (
    "os"
    "text/template"
)

// .Path won't be accessible, because dot will be changed to the Files element
const page = `{{range .Files}}<script src="{{html .Path}}/js/{{html .}}"></script>{{end}}`

type scriptFiles struct {
    Path string
    Files []string
}

func main() {
    t := template.New("page")
    t = template.Must(t.Parse(page))

    t.Execute(os.Stdout, &scriptFiles{"/var/www", []string{"go.js", "lang.js"}})
}

play.golang.org

  • 写回答

1条回答 默认 最新

  • donglian7879 2013-06-24 20:24
    关注

    Using the $ variable (recommended)

    From the package text/template documentation:

    When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.

    As @Sandy points out, it is therefore possible to access the Path in the outer scope using $.Path.

    const page = `{{range .Files}}<script src="{{html $.Path}}/js/{{html .}}"></script>{{end}}`
    

    Using a custom variable (old answer)

    Found one answer just minutes after posting.
    By using a variable, a value can be passed into the range scope:

    const page = `{{$p := .Path}}{{range .Files}}<script src="{{html $p}}/js/{{html .}}"></script>{{end}}`
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址