美文网首页
go template 基本语法

go template 基本语法

作者: wkmx | 来源:发表于2019-06-13 11:09 被阅读0次

    html/template 基本语法

    创建一个模板

    var t *template.Template
    t, _ = t.Parse(``)
    

    输出

    `{{ . }}` 输出
    

    调用结构的方法

    `{{ .Say "hello }}`
    

    模板中定义变量

    `{{ $a := "模板中的变量" }}`
    

    模板函数

    t.Funcs(template.FuncMap{"test1": test1}) 注册函数
    t.Funcs(template.FuncMap{"test2": test2});
    
    {{ 函数名 }} 输出函数返回值
    {{ 函数名 参数1 参数2 }}
    
    {{ .字段  名 | 函数名 }} 以字段的值作为函数的参数
    
    t.Parse(`{{test1}}
        {{ test2 "参数" }})
        {{.UserName | test2 }}
        `)
    t.Execute(os.Stdout, Person{})
    

    条件判断

    {{ if 1 }} true  {{ else }} {{ end }}
    

    遍历

        {{ range $k, &v := .Map }}
            {{ $k }} {{ $v }}
        {{ end }}
    
        {{ range $index, &article :=  .article}} 
            {{ $index}} // 索引, 默认从0开始, 如果需要从1开始, 可以注入自定义函数进来
        {{ end }}
    

    嵌套模板

        {{ define "tp1" }} I'm template 1 {{ end }}
        {{ define "tp2" }} I'm template 2 {{ . }} {{ end }}
        {{ define "tp3" }} {{ template "tp1"}} {{ template "tp2" }} {{ end }}
        {{ template "tp1" }}
        {{ template "tp2" "test1" }}
    
        {{ template "tp3" "test1" }}
    

    内置的模板函数

    {{ and 3 4 }} //如果3为真, 返回4, 否则返回3
    
    {{ or 3 4 }} // 如果3位真, 返回3, 否则返回4
    
    {{ call sum 1 3 5 7 }} // call 后的第一个参数的返回值必须是一个函数
    
    {{ "<br>"|html}} // 转义文本中html的标签
    
    {{index .Contact "qq"}} // 返回 Contact 索引为qq的值
    
    {{ "?a=123&b="你好"|js}} //   返回用js的escape处理后的文本, 自动进行html转义
    
    {{"hello"|len}} // 返回参数的长度
    
    {{ not 0 }} // bool 取反
    
    {{"你好"|print "世界"}} // fmt.Sprint 的别名
    
    {{"你好"|printf "%d %s" 123}} // Spintf的别名
    
    {{"你好"|println "世界"}} // Println
    
    {{?q=关键字&p=1|urlquery}} // 进行url编码
    
    {{ if eq 1 1}} 等于
        - eq 等于
        - ne 不等于
        - lt 
        - le 
        - gt
        - ge
    

    相关文章

      网友评论

          本文标题:go template 基本语法

          本文链接:https://www.haomeiwen.com/subject/dsujfctx.html