html
vuejsonjshtmlhtmlhtmliframe
这里使用的是第二种方式。
gohtml
常见的模板引擎一般有两种实现方式,一种是直接解析 HTML 语法树,然后根据一定的规则动态的拼接,另外一种是把模板预先生成代码,渲染模板时调用相关的函数即可。
gotemplate
hero 简介
可以直接去 github 上看,这里做一个简短的介绍。
安装
go get github.com/shiyanhui/hero
go get github.com/shiyanhui/hero/hero
// Hero需要goimports处理生成的go代码,所以需要安装goimports.
go get golang.org/x/tools/cmd/goimports
使用
hero [options]
options:
- source: 模板目录,默认为当前目录
- dest: 生成的go代码的目录,如果没有设置的话,和source一样
- pkgname: 生成的go代码包的名称,默认为template
- extensions: source文件的后缀, 如果有多个则用英文逗号隔开, 默认为.html
- watch: 是否监控模板文件改动并自动编译
example:
hero -source="./"
hero -source="$GOPATH/src/app/template" -watch
基本语法
Hero
<%!
import (
"fmt"
"strings"
)
var a int
const b = "hello, world"
func Add(a, b int) int {
return a + b
}
type S struct {
Name string
}
func (s S) String() string {
return s.Name
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<%@ body { %>
<% } %>
</body>
</html>
<% for _, user := range userList { %>
<% if user != "Alice" { %>
<%= user %>
<% } %>
<% } %>
<%
a, b := 1, 2
c := Add(a, b)
%>
<%== "hello" %>
<%==i 34 %>
<%==u Add(a, b) %>
<%==s user.Name %>
<%= a %>
<%= a + b %>
<%= Add(a, b) %>
<%= user.Name %>
原理
io.Writer
func WriteTreeNodeHtml(param *RenderTemplateParam, w io.Writer) {
_buffer := hero.GetBuffer()
defer hero.PutBuffer(_buffer)
_buffer.WriteString(`
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/build.css" />
<link rel="stylesheet" href="css/jquery.treeview.css" />
<link rel="stylesheet" href="css/screen.css" />
<script src="js/jquery.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script src="js/jquery.treeview.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#tree").treeview({
collapsed: true,
animated: "fast",
control: "#sidetreecontrol",
prerendered: true,
persist: "location"
});
})
</script>
</head>
<body style="margin: 10px;">
<div>
<h3>`)
hero.EscapeHTML(GetAppName(), _buffer)
_buffer.WriteString(`报告</h3>
<div id=jstree style="font-size:14px">
<ul class="treeview" id="tree" style="margin-top:6px;">
<li><a class="jstree-anchor" href="page1.html#case" target="pageframe">
<i style="margin-left: 4px;margin-right: 4px;" class="icon-file iconfont"></i>案件</a></li>
<li><a class="jstree-anchor" href="page1.html#evidences" target="pageframe">
<i style="margin-left: 4px;margin-right: 4px;" class="icon-evidence iconfont"></i>检材信息</a></li>
<li><a class="jstree-anchor" href="page1.html#brief" target="pageframe">
<i style="margin-left: 4px;margin-right: 4px;" class="icon-evidence iconfont"></i>数据统计文字概括</a></li>
<li><a class="jstree-anchor" href="page1.html#summary" target="pageframe">
<i style="margin-left: 4px;margin-right: 4px;" class="icon-summary iconfont"></i>数据统计清单</a></li>
`)
treeNodes, ok := param.Data.([]*ReportTreeNode)
if !ok {
return
}
for _, node := range treeNodes {
GenerateTreeNode(node, _buffer)
}
_buffer.WriteString(`
</ul>
</div>
</div>
</body>
</html>
`)
w.Write(_buffer.Bytes())
}
总结
gohtmlhtml
参考