Go模板引擎,也可以在浏览器中运行。

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

Go templating engine that also runs in the browser

问题

我正在开发一个使用Go语言的Web应用程序,路由器将使用PushState,因此服务器也必须能够渲染我的模板。这意味着我需要一个能够与Go和JavaScript一起工作的模板引擎。到目前为止,我只找到了一个叫做Mustache的模板引擎,但它似乎不能处理结构体的小写属性,并且也没有提供自定义名称的可能性,比如JSON中的名称:

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

那么,有没有一个模板引擎可以在Go和JavaScript中使用,并且可以处理小写结构体属性呢?

英文:

I'm developing a web application with Go on the server, and the router will use PushState, so the server will also have to be able to render my templates. That means that I'll need a templating engine that works with Go and Javascript. The only one I've come across so far is Mustache, but it doesn't seem to be able to handle lowercase properties of structs, and there also doesn't seem to be a possibility to provide custom names like JSON:

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

So, is there a templating engine that is available in both Go and JavaScript, and that can handle lowercase struct properties?

答案1

得分: 0

如上面的评论所述,你不能指望任何第三方库能够读取你结构体中的小写属性,但是你似乎想要使用标签来表示结构体的替代表示(就像encoding/json库一样)。

你可以使用github.com/fatih/structs这样的库将你的结构体转换为映射,然后遍历映射将所有的键转换为小写(复制值并删除大写版本),然后将其作为上下文传递给mustache.Render()。如果你想要像encoding/json库那样使用结构体标签,你需要使用reflect包并编写一个结构体到映射的函数,该函数考虑结构体上的标签(文档中给出了一个基本示例)。有一些关于如何使用反射编写结构体到映射函数的stackoverflow答案,你可以根据需要改进并添加结构体标签处理。

回答你的问题,我认为目前没有一个同时与JavaScript一起工作的模板库可以做到这一点,但是根据上面的思路,使用mustache应该不难实现。

英文:

As the comments above state, you can't expect any 3rd party library to be able to read lowercase properties on your struct, but it appears you are trying to use tags to represent alternative representations of your struct (as you can with the encoding/json library).

What you can do is use something like github.com/fatih/structs to convert your structs to maps and then range through to lowercase all of your keys (copying the values and removing the uppercase versions) and pass it into mustache.Render() as your context. If you want to use struct tags like the encoding/json library does, you'd have to use the reflect package and write a struct-to-map function that takes into account the tags on the struct (basic example given in the documentation here). There are some SO answers on how to write a struct-to-map function using reflection, which you can improve upon to add struct tag handling as you need.

To answer your question, I don't think this is something a current templating library does that also works with javascript, but it shouldn't be too hard to get working with mustache given the idea above.

huangapple
  • 本文由 发表于 2015年4月9日 00:14:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/29519958.html
匿名

发表评论

匿名网友

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

确定