模板基本语法不是本文的重点,本章节只阐述常用基本语法,其他语法请自行网络查阅相关知识。
我们需要将自动以函数统一管理起来,这个管理模块在restgo/Func.go中,该模块已经内置了ctxpath、version等常用方法,那么如果需要定制一个新的方法,该怎么做呢?以hello方法为例
要使用自定义hello函数,首先需要在restgo/Func.go中添加hello函数,如下
func init(){ restFuncMap["ctxpath"]=ctxpath restFuncMap["pageurl"]=pageurl restFuncMap["apiurl"]=apiurl restFuncMap["version"]=version restFuncMap["hello"]=hello}func GetFuncMap()(template.FuncMap){ return restFuncMap}func hello(d string) string{ return "hello "+d}
在view/user目录下新建hello.html,我们以如下方式调用该方法
{{define "user/hello.html"}}<!DOCTYPE html><html> <head> </head> <body> {{hello "restgo"}} </body></html>{{end}}
请求结果如下
C:\Users\Administrator>curl localhost/user/hello.shtml
<!DOCTYPE html><html><head></head><body>hello restgo</body></html>
在freemarker 或者jsp中我们非常熟悉include方法,该方法对菜单处理,公用头部文件和尾部文件等公用模板文件处理非常方便和快捷,在golang中,也有类似方法,他就是template。以如下布局为例。
图中head、left、foot区域是公共的,不同的是content区域,那么我们抽象如下模板
//public/head.html{{define "public/head.html"}}这里是head区域内容{{end}}//public/foot.html{{define "public/foot.html"}}这里是foot区域内容{{end}}//public/left.html{{define "public/left.html"}}这里是left区域内容{{end}}//public/content.html{{define "public/content.html"}} <html> <head> </head> <body>{{template "public/head.html"}}{{template "public/left.html"}}<div class="content"> 这里是具体内容 </div>{{template "public/foot.html"}} </body> </html>{{end}}
为了便于将来实现动静态分离,我们可以扩展一个asset方法,用于制定静态资源路径
func init(){ restFuncMap["ctxpath"]=ctxpath restFuncMap["pageurl"]=pageurl restFuncMap["apiurl"]=apiurl restFuncMap["version"]=version restFuncMap["hello"]=hello restFuncMap["asset"]=asset}func asset(d string) string{ cfg := GetCfg() return cfg.App["protocal"]+"://" + cfg.App["asset"]}
摸板中以如下方式调用
<link rel="stylesheet" href="{{asset}}/assets/plugins/font-awesome/css/font-awesome.min.css"><!-- Ionicons --><link rel="stylesheet" href="{{asset}}/assets/plugins/ionicons/css/ionicons.min.css">
当资源文件迁移时,我们可以直接修改如下配置
#静态资源所在的服务器地址,便于动静态分离restgo.app.asset=localhost
本文源代码源代码获取地址 https://github.com/winlion/restgo
10.2 天天任务清单小程序
https://github.com/winlion/dailytask
10.3 工业大数据采集
10.4 restgo cms
10.5 restgo 千人大群
作者简介:胡文林,持续创业者,长期从事技术开源工作。微信号jiepool-winlion
