【问题标题】:In a template how do you access an outer scope while inside of a "with" or "range" scope?在模板中,如何在“with”或“range”范围内访问外部范围?
【发布时间】:2013-02-10 17:03:47
【问题描述】:

当在withrange 中时,. 的范围会发生变化。如何访问调用范围?

【问题讨论】:

    标签: go go-templates


    【解决方案1】:
    {{with .Inner}}
      Outer: {{$.OuterValue}}
      Inner: {{.InnerValue}}
    {{end}}
    

    $ 记录在 text/template 文档中:

    开始执行时,$ 设置为传递给 Execute 的数据参数,即设置为 dot 的起始值。

    【讨论】:

      【解决方案2】:

      您可以使用变量保存调用范围:

      {{ $save := . }}
      {{ with .Inner }}
        Outer: {{ $save.OuterValue }}
        Inner: {{ .InnerValue }}
      {{ end }}
      

      【讨论】:

        猜你喜欢
        • 2016-06-23
        • 2011-06-01
        • 1970-01-01
        • 2016-11-06
        • 1970-01-01
        • 2021-08-18
        • 1970-01-01
        • 1970-01-01
        • 2023-04-07
        相关资源
        最近更新 更多