golang 的模板引擎
text/templateiris
github.com/flosch/pongo2
<html>
<head>
<title>{{title}}</title>
</head>
<body>
<!--过滤器-->
<h1>Hi {{name|capfirst}} </h1>
<!-- 取值 -->
<h3>Server started about {{serverStartTime}}. Refresh the page to see different result</h3>
<!-- 循环 -->
{% for item in userList %}
<p>{{item}}</p>
{%endfor%}
<!-- 条件判断 -->
i的值是:{{i}}<br/>
{% if i>1 %}
i大于1
{%elif i==1%}
i等于1
{%elif i<1 and i>0 %}
i介于0和1之间
{%else%}
i小于0
{%endif%}
</body>
</html>
package main
/**
https://github.com/flosch/pongo2
支持Django 1.7模板语法
*/
import (
"fmt"
"github.com/flosch/pongo2"
)
func main() {
// 从字符串格式化案例
fromString()
// 从文件读取格式化
fromFile()
}
func fromFile() {
tpl,err := pongo2.FromFile("./templates/hi.html")
if err!=nil {
panic(err)
}
var userList = []string{
"Alice",
"Bob",
"Tom",
}
var i = 5
out,err := tpl.Execute(pongo2.Context{
"title": "Hi Page",
"name": "iris",
"userList": userList,
"i": i,
})
fmt.Println(out)
}
func fromString() {
// Compile the template first (i. e. creating the AST)
tpl, err := pongo2.FromString("Hello {{ name|capfirst }}!")
if err != nil {
panic(err)
}
// Now you can render the template with the given
// pongo2.Context how often you want to.
out, err := tpl.Execute(pongo2.Context{"name": "florian"})
if err != nil {
panic(err)
}
fmt.Println(out) // Output: Hello Florian!
}