gtpl go语言html渲染

pywee · · 1653 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

### gtpl 可以灵活的替代 html/template 包。变量和函数调用更加方便。支持 if else elseif a.go 文件 ``` data := &Dat a{ Id: 1, WebTitle: "WebTitle", Winner: &Demo{ Str: "pywee", }, Users: []*User{ { Id: 1, UserName: "Jim", MyList: []*UserCustom{ {PhoneNumber: "1"}, {PhoneNumber: "2"}, }, }, { Id: 2, UserName: "Lucy", MyList: []*UserCustom{ {PhoneNumber: "1"}, {PhoneNumber: "2"}, }, }, }, } // http server example http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { // 实例化gtpl (instantiation gtpl) p := templates.NewParser() // 引入模板文件,将 data 数据匹配模板中的调用 re, err := p.ParseFile("index.html", data) if err != nil { panic(err) } // print string // fmt.Println(re.String()) // 输出到屏幕,它的作用相当于 template.Excute(w, "%s", data) re.Fprint(w) }) ``` <br /> index.html ``` // 访问Id 和 WebTitle字段 {:id} {:web_title} // 访问 Data 结构体中的 Other.Demo.Str // to call Other.Demo.Str of struct Data {:winner.str} // 在访问字段的同时,执行内置函数 {:trim(replace(title, "i am", "xx", -1), "xx")} // 对于列表处理,例如循环 data 下的 users 数组,用如下方式 {:id} {:winner.str} // 访问 Data 下的 Winner结构体,再访问该结构体下的 Str 字段 {!list:users} {!if id==(1*1+1-1-1)} man: {:user_name} {;elseif 1==21} women: {:user_name} {;else} {!list:my_list} {:phone_number} {/list} {/if} {/list} </html> ``` https://github.com/pywee/gtpl

有疑问加站长微信联系(非本文作者))

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1653 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传