美文网首页
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 基本语法

    html/template 基本语法 创建一个模板 输出 调用结构的方法 模板中定义变量 模板函数 条件判断 遍历...

  • Go template 语法简介

    使用kubernetes helm部署服务,遇到template文件定义需要使用“或”的场景,查到原来helm t...

  • beego 模版语法

    beego 模板语法指南 本文讲述 beego 中使用的模板语法,与 go 模板语法基本相同。 基本语法 go 统...

  • (四)go语言函数&参数传递

    go语言函数 基本语法 例子 go语言参数传递

  • 最详细的Golang Template 模板语法说明

    Go提供了template 库专门用于渲染模板输出,语法如下: 查看全文: http://www.golang.r...

  • go 基本语法

    数据类型: 告诉编译器这个数(变量)应该以多大的内存存储 命名规范: 1) 字母,下划线,数字 2) 不能以数字开...

  • GO基本语法

    变量 变量可以认为是程序在内存中申请一块数据存储空间的名称, 程序常常声明一个变量, 然后再内存中申请一块空间, ...

  • go基本语法

    一、总结 1、Go没有对象,没有继承多台,没有泛型,没有try/catch2、Go有接口,函数式编程,csp并发模...

  • GO基本语法

    //GO基本语法介绍 package main // 声明main包 import( // 导入...

  • go基本语法

    首先 下载vscode并安装go插件;下载go源码(从golang中国社区)选windows-amd64的哪个解压...

网友评论

      本文标题:go template 基本语法

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