douaikuai2715 2017-01-08 15:13
浏览 240
已采纳

Golang模板-在范围循环内将模板变量用作全局变量

I will try to make this as simple as possible. I have two variables in Golang which are parsed to the template file.

Here is my Golang code which declares the variables:

for _, issue := range issues {
    issueIDStr := strconv.Itoa(*issue.ID)
    parse[*issue.ID] = issueIDStr 
    parse[issueIDStr+"-label"] = "blah blah"
}

Then in my HTML file:

{{ range .issues }}
    <!-- Here I want to use the current issue's ID as a global variable which is outside the range loop -->
    <!-- According to the Golang doc which says the following:
             When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.
         I can use $.Something to access a variable outside my range loop right...
         but how can I use a template variable as a global variable? I tried the following which doesn't work.
    {{ $ID := .ID }}
    <p>{{ index $.$ID "author" }}</p>
{{ end }}

After running this code, I get the error: bad character U+0024 '$' along with a panic thrown.

Is what I am attempting completely impossible currently, or is there some trick I am missing?

Thanks :)

  • 写回答

1条回答 默认 最新

  • dqxyh48864 2017-01-08 23:00
    关注

    You should simply make a map[string]interface{} containing the issues array and then use that as the template execution data.

    Then you can loop over the issues and directly access its' members from the template.

    Here's a small complete example:

    const t = `
    {{ range .issues }}
    issue: {{ .ID }}
        author: {{ .Author }}
    {{ end }}
    `
    
    type Issue struct {
        ID     int
        Author string
    }
    
    func main() {
        issues := []Issue{{1, "Pepe"}, {2, "Cholo"}}
        data := map[string]interface{}{"issues": issues}
        tpl := template.Must(template.New("bla").Parse(t))
        tpl.Execute(os.Stdout, data)
    }
    

    Which outputs:

    issue: 1
            author: Pepe
    
    issue: 2
            author: Cholo
    

    Additionally if you want/need to add data specific to the template rendering process you should define a "rich" issue struct for this purpose and transform your model before passing it to template execution. This could be done for both statically known extra data (as simple members of RichIssue) and for dynamically loaded data (as key/values of a map).

    Here's an extended example showing the above suggestions:

    const t = `
    {{ range .issues }}
    issue: {{ .ID }}
        author: {{ .Author }}
        static1: {{ .Static1 }}
        dyn1: {{ .Data.dyn1 }}
    {{ end }}
    `
    
    type Issue struct {
        ID     int
        Author string
    }
    
    type RichIssue struct {
        Issue
        Static1 string                 // some statically known additional data for rendering
        Data    map[string]interface{} // container for dynamic data (if needed)
    }
    
    func GetIssueStatic1(i Issue) string {
        return strconv.Itoa(i.ID) + i.Author // whatever
    }
    
    func GetIssueDyn1(i Issue) string {
        return strconv.Itoa(len(i.Author)) // whatever
    }
    
    func EnrichIssue(issue Issue) RichIssue {
        return RichIssue{
            Issue:   issue,
            Static1: GetIssueStatic1(issue),
            // in this contrived example I build "dynamic" members from static
            // hardcoded strings but these fields (names and data) should come from
            // some kind of configuration or query result to be actually dynamic
            // (and justify being set in a map instead of being simple static
            // members as Static1)
            Data: map[string]interface{}{
                "dyn1": GetIssueDyn1(issue),
                "dyn2": 2,
                "dyn3": "blabla",
            },
        }
    }
    
    func EnrichIssues(issues []Issue) []RichIssue {
        r := make([]RichIssue, len(issues))
        for i, issue := range issues {
            r[i] = EnrichIssue(issue)
        }
        return r
    }
    
    func main() {
        issues := []Issue{{1, "Pepe"}, {2, "Cholo"}}
        data := map[string]interface{}{"issues": EnrichIssues(issues)}
        tpl := template.Must(template.New("bla").Parse(t))
        tpl.Execute(os.Stdout, data)
    }
    

    Which produces the following output:

    issue: 1
        author: Pepe
        static1: 1Pepe
        dyn1: 4
    
    issue: 2
        author: Cholo
        static1: 2Cholo
        dyn1: 5
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)