text html template遍历,golang text/template的详细说明

golang text/template讲解概述运行过程要求遍历structtext 和spacesActionsArgumentsPipelineVariablesPilelines和Variables例子FunctionsExamples更多

概述

text/template实现基于数据的文本化输出。功能和jsp、blade.php(laravel)一样,用于动态生成文件,只不过golang用于生产HTML的模块为html/template1

运行过程

将template模板应用于结构化的数据,使用注解语法引用数据结构中的元素(struct中的feild或map中的key)并显示它们的值。template在执行过程中遍历数据结构并且设置当前光标(英文句号“.”标识)标识当前位置的元素(值)

一旦解析,模板可以安全地并行执行,但是如果并行执行共享Writer,则输出可以是交错的。

要求

template的文本必须为UTF-8编码。注解语法必须由“{ {”和“}}”分隔,不在“{ {”和“}}”的文本原样输出。一般来说注解语法不用另起一行,可以和非注解文本同行,不过如果是动态注释的话,注解语法还是建议另起一行。

遍历struct

type Inventory struct {

Material string

Count uint

}

sweaters := Inventory{"wool", 17}

tmpl, err := template.New("test").Parse("{ {.Count}} items are made of { {.Material}}")

if err != nil { panic(err) }

err = tmpl.Execute(os.Stdout, sweaters)

if err != nil { panic(err) }

上面的例子中模板test变量sweaters中的Count和Material域,“.Count”中的“.”标识sweaters根元素

执行结果

➜ template git:(master) ✗ go run text_template.go

17 items are made of wool%

text 和spaces

虽然所有在“{ {}}”控制注解之外的文本会默认一分不差地复制到输出中,但是如果“{ {”紧接着跟随“—”和“ ”的话,那么“{ {”之前的文本中的空白(空格、换行符、回车符、制表符)会被移除。对应的,“ -}}”表示移除之后文本中的空白。

例如上面例子,稍作修改:

package main

import (

"os"

"text/template"

)

type Inventory struct {

Material string

Count uint

}

func main(){

sweaters := Inventory{"wool", 17}

tmpl, err := template.New("test").Parse("{ {.Count -}} items are made of { {- .Material}}")

if err != nil { panic(err) }

err = tmpl.Execute(os.Stdout, sweaters)

if err != nil { panic(err) }

}

执行结果:

➜ template git:(master) ✗ go run text_template.go

17items are made

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值