Templates.ExecuteTemplate(w, "index.html", map[string]interface{} {
"Games": games})
}
games 是 []map[string]interface{}
(sql 查询的映射结果)
在模板中:
{{ range $gval := .Games }}
{{ how to make something like: $gval.name.(string) }}
{{end}}
如何在模板中将 map 的 interface{} 值转换为字符串(或整数)?在'去'我可以做
游戏[0]["name"].(string)
当我执行 $gval.name
时,它会写入十六进制字符串
最佳答案
我认为不可能从模板中进行类型断言。您必须编写自己的函数并从模板中调用它。例如:
func ToString(value interface{}) string {
switch v := value.(type) {
case string:
return v
case int:
return strconv.Itoa(v)
// Add whatever other types you need
default:
return ""
}
}
为了能够从模板调用函数,您必须在模板上调用 Funcs() 方法:
tpl.Funcs(template.FuncMap{"tostring": ToString})
现在你可以做 {{$gval.name | tostring}}
在你的模板中
关于go - Cast interface{} 以输入模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38457755/