gtpl go语言html渲染


本文摘自网络,作者pywee,侵删。

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)
    })


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


相关阅读 >>

asta:是什么终结了我的鸽王生涯?Go 1.13 发布!

python、Golang、java、c++哪个薪资高?小白必看!

Golang map 不排序怎么办

Golang 定时器详解

Golang快不快

手撸Golang 行为型设计模式 备忘录模式

leetcode232 用栈实现队列 Golang

2021年放弃python选择Go的原因

rabbitmq 消息丢失处理机制 confirm模式 [Go 版本]

如何读取yaml,json,ini等配置文件【Golang 入门系列九】

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...