简体   繁体   English

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

[英]Go templating engine that also runs in the browser

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. 我正在服务器上使用Go开发Web应用程序,路由器将使用PushState,因此服务器还必须能够呈现我的模板。 That means that I'll need a templating engine that works with Go and Javascript. 这意味着我需要一个可以与Go和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: 到目前为止,我遇到的唯一一个是Mustache,但它似乎无法处理结构的小写属性,而且似乎也无法提供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? 那么,Go和JavaScript中是否都有可用的模板引擎,并且可以处理小写的struct属性?

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). 就像上面的评论指出的那样,您不能指望任何第三方库都能够读取结构上的小写字母属性,但是您似乎正在尝试使用标签来表示结构的其他表示形式(如encoding/json库)。

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. 您可以做的是使用github.com/fatih/structs东西将您的结构转换为地图,然后将所有键都转换为小写(复制值并删除大写版本)并将其传递给mustache.Render()作为您的上下文。 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 ). 如果要像encoding/json库一样使用struct标记,则必须使用reflect包并编写一个考虑到struct标记的struct-to-map函数( 此处提供了基本示例) )。 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. 关于如何使用反射编写从结构到映射的函数,有一些SO答案,您可以根据需要对其进行改进以添加结构标记处理。

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. 要回答您的问题,我不认为这是当前的模板库也可以与javascript一起使用的东西,但是考虑到上述想法,使用胡子也不应该太难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM