The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
sunmoon1983

golang 的模板中可以通过动态的 key 取 map 中的值吗?

  •  
  •   sunmoon1983 · Mar 24, 2021 · 2548 views
    This topic created in 1882 days ago, the information mentioned may be changed or developed.

    我有一个 slice

    keyList:=[ "2021-02", "2020-08", "2020-07", "2020-05", "2020-02", "2020-01", ]
    

    还有一个 map

    dataMap := map[string]int{
    "2021-02":123,
    "2020-08":234,
    "2020-07":234234,
    "2020-05":23423,
    "2020-02":345345345,
    "2020-01":456456,
    }
    

    想在模板中通过循环 slice 得到 map 中的值 比如

    {{range $index, $date := .keyList}}
        {{if .dataMap.$date}} # 这里貌似不对呀,不知道应该怎么取
            {{range $key,$item := .dataList.$date}}
            <p>{{$date}}:{{$item}}</p>
            {{end}}
        {{end}}
    {{end}}
    
    5 replies    2021-03-24 09:35:07 +08:00
    nanjishidu
        1
    nanjishidu  
       Mar 24, 2021
    好像遇到过 模板中先声明赋值一下 datamap
    imherer
        3
    imherer  
       Mar 24, 2021
    ````
    for _, key := range keyList {
    fmt.Println(dataMap[key])
    }
    ````
    不知道为什么 贴完整代码提示要验证手机,那就贴关键部分吧
    imherer
        4
    imherer  
       Mar 24, 2021
    @imherer 不好意思看错了,说的是模板
    sunmoon1983
        5
    sunmoon1983  
    OP
       Mar 24, 2021
    谢谢大家,我找到方法了
    ```
    {{range $item := index $.dataList $date}}
    <li><b></b><span>{{$item.created_at | date "m-d"}}:<a href="{{$item.url}}">{{$item.title}}</a> </span></li>
    {{end}}
    ```
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5278 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 08:42 · PVG 16:42 · LAX 01:42 · JFK 04:42
    ♥ Do have faith in what you're doing.