英文:
Go html template how to get user IP in function from funcMap
问题
我知道如何从*http.Request
结构中获取用户的IP:
strings.Split(r.RemoteAddr, ":")[0]
我也知道如何定义一个template.FuncMap
:
funcMap = template.FuncMap{
// 获取帖子发布后的时间
"since": func(t time.Time) string {
s := time.Since(t).String()
return strings.Replace(s[:strings.LastIndex(s, "m")+1], "h", "h ", 1)
},
}
如何从在template.FuncMap
中定义的模板函数中获取用户的IP?
英文:
I know how to get the user IP from the *http.Request
struct:
strings.Split(r.RemoteAddr, ":")[0]
And I know how to define a template.FuncMap
:
funcMap = template.FuncMap{
// gets the time since the post was posted
"since": func(t time.Time) string {
s := time.Since(t).String()
return strings.Replace(s[:strings.LastIndex(s, "m")+1], "h", "h ", 1)
},
}
How would I get the users IP from a template function defined in the template.FuncMap
?
答案1
得分: 2
func map是用于辅助函数的,而不是用于数据,应该在解析模板之前定义一次,所以这不是一个好的位置。相反,当执行模板时,应该将数据传递给视图。
这个功能更适合在视图的数据/上下文中。例如,如果你在那里使用map[string]interface{}(我会使用interface{}的少数几个地方之一),你可以简单地在那里分配它:
userIP := strings.Split(r.RemoteAddr, ":")[0]
data := map[string]interface{}{"userIP": userIP}
err := tmpl.Execute(w, data)
模板:
用户IP:{{.userIP}}
英文:
The func map is intended for helper functions, rather than data, and should be defined once before parsing templates, so this isn't a good place for it. You should instead pass in the data to the view when executing the template.
This would fit better in your data/context for the view. For example if you use a map[string]interface{} for that (one of the few places I'd use interface{}), you can simply assign it there:
userIP := strings.Split(r.RemoteAddr, ":")[0]
data := map[string]interface{}{"userIP":userIP}
err := tmpl.Execute(w,data)
Template:
<p>User IP:{{.userIP}}</p>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论