In Go templates, accessing parent/global pipeline within range

前端 未结 1 1596
盖世英雄少女心
盖世英雄少女心 2021-01-01 09:28

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,

相关标签:
1条回答
  • 2021-01-01 10:04

    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}}`
    
    0 讨论(0)
提交回复
热议问题