How do you define view model in Go

huangapple go评论103阅读模式
英文:

How do you define view model in Go

问题

我想为视图模型定义一个结构,类似于:

type AdminView struct {
	PageTitle string
	UserName string
	UserType string
	Templates []Template
	...
	OtherAttr Other
}

这样可以更好地帮助我组织模板和数据传输对象(DTO),但是到目前为止效果不太好。我想要实现的效果是这样的:

func adminViewHandler(w http.ResponseWriter, r *http.Request) {
	data := processRequestData(r) // 处理请求表单数据
	view := AdminView{}
	// 然后给视图赋值
	view.render(w) // 类似于 tmpl.Exec(w, data)
}

我想知道我是否在通过上述方法引入更多的抽象来渲染视图方面走在了正确的轨道上。我也想了解现实世界中人们如何渲染复杂视图和复杂数据。

提前感谢。

英文:

I would like to define a structure for View model, something looks like:

type AdminView struct {
	PageTitle string
	UserName string
	UserType string
	Templates []Template
	...
	OtherAttr Other
}

to help me organize templates and DTO better, but haven't worked very well so far. What I want to achieve is something like this:

func adminViewHandler (w http.ResponseWriter, r *http.Request) {
	data := processRequestData (r)  // process request form data
	view := AdminView {}
	// then assign values to view
	view.render(w) // similar to tmpl.Exec(w, data)
}

I'd like to know if I am on the right track to introduce more abstraction in rendering the View using the approach above. I would like to know how people render complex view with complex data in real world, too.

Thanks in advance.

答案1

得分: 2

你差不多走对了。记住,Go语言不是面向对象的语言,所以继承(你试图做的)不是一个非常常见的模式。

相反,你可以使用模板,并将视图模型传递到模板中:

view := AdminView{}
...
tmpl.Exec(w, view)
英文:

You're almost on track. Remember that Go is not an object-oriented language, so inheritance (what you're trying to do) is not a very common pattern.

Instead what you would do is use a template, and pass the view model into the template:

view := AdminView{}
...
tmpl.Exec(w, view)

huangapple
  • 本文由 发表于 2017年5月24日 22:54:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/44161983.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定