英文:
In Golang, how do I define a specific sort of map as a unique type?
问题
所以我现在处于一个尴尬的境地,我正在尝试将上下文数据传递给模板,但是没有太多真正好的例子,这些例子不涉及传递预先存在的结构。我能想到的最好的方法是像下面这样:
templ.Execute(writer, map[string]interface{}{
"thingyA": ThingyA,
"thingyB": ThingyB,
})
使用上述方法,我可以通过{{ .thingyA.[PROPERTY] }}
在模板中引用ThingyA
及其所有属性和方法。这本身就很好,因为它允许我以简单的Django风格定义上下文,而不使用匿名结构,这会有点笨拙。
但是我想知道是否有一种方法可以定义一个新类型Context
,这样我就可以简化上述代码,如下所示:
templ.Execute(writer, Context{
"thingyA": ThingyA,
"thingyB": ThingyB,
})
也就是说,我想定义一个特定类型的Context
,它始终具有map[string]interface{}
的形式,并且可以像初始化映射一样进行初始化。有关如何实现这一点的任何想法吗?
英文:
So I'm at that awkward place where I'm trying to pass context data over to a template, and there's not a whole lot of really great examples out there that don't involve passing a preexisting structure. The best I have come up with is something like the following:
templ.Execute(writer, map[string]interface{}{
"thingyA": ThingyA,
"thingyB": ThingyB,
})
Using the above, I can reference ThingyA
and all of its properties and methods in my template by using {{ .thingyA.[PROPERTY] }}
. So that's pretty good in itself, in that it allows me to define a context in a simple Django-ish fashion, without using an anonymous struct, which would be a bit clunky.
But I'm wondering if there is some way to define a new type Context
, so that I could simplify the above to the following:
templ.Execute(writer, Context{
"thingyA": ThingyA,
"thingyB": ThingyB,
})
That is, I would like to define a specific type Context
that always has the form map[string]interface{}
, and can be initialized in the same manner as a map. Any ideas on how to go about this?
答案1
得分: 4
type Context map[string]interface{}
c := Context{"foo": 1, "bar": 2}
英文:
type Context map[string]interface{}
c := Context{"foo": 1, "bar": 2}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论