Package template

import "text/template"
Overview
Index
Examples
Subdirectories

Overview ▾

包模板实现了数据驱动的模板以生成文本输出.

要生成HTML输出,请参阅html / template软件包,该软件包具有与此软件包相同的接口,但会自动保护HTML输出免受某些攻击.

通过将模板应用于数据结构来执行模板. 模板中的注释是指数据结构的元素(通常是结构的字段或映射中的键),以控制执行并派生要显示的值. 执行模板将遍历结构并设置光标,并用句点"."表示. 并在执行过程中将其称为"点"到结构中当前位置的值.

模板的输入文本是UTF-8编码的任何格式的文本. "操作"(数据评估或控制结构)由" {{"和"}}"界定; 所有外部动作文本将原样复制到输出中. 除了原始字符串,动作可能不会跨越换行符,尽管注释可以.

解析后,可以并行安全地执行模板,尽管如果并行执行共享一个Writer,则输出可以交错.

这是一个简单的示例,上面印有" 17件是羊毛做的".

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

下面显示了更复杂的示例.

Text and spaces

By default, all text between actions is copied verbatim when the template is executed. For example, the string " items are made of " in the example above appears on standard output when the program is run.

但是,为帮助格式化模板源代码,如果操作的左定界符(默认情况下为" {{")后紧跟一个减号和ASCII空格字符(" {{-"),则会从紧接在前的文本. 同样,如果右定界符("}}")前面有一个空格和减号("-}}"),则所有紧随其后的空格均会紧随其后的文本. 在这些修饰标记中,必须存在ASCII空格; " {{-3}}"解析为包含数字-3的动作.

例如,执行源为

"{{23 -}} < {{- 45}}"

生成的输出将是

"23<45"

对于这种修剪,空格字符的定义与Go中的相同:空格,水平制表符,回车符和换行符.

Actions

这是动作列表. "参数"和"管道"是对数据的评估,将在随后的相应部分中详细定义.

{{/* a comment */}}
{{- /* a comment with white space trimmed from preceding and following text */ -}}
	A comment; discarded. May contain newlines.
	Comments do not nest and must start and end at the
	delimiters, as shown here.

{{pipeline}}
	The default textual representation (the same as would be
	printed by fmt.Print) of the value of the pipeline is copied
	to the output.

{{if pipeline}} T1 {{end}}
	If the value of the pipeline is empty, no output is generated;
	otherwise, T1 is executed. The empty values are false, 0, any
	nil pointer or interface value, and any array, slice, map, or
	string of length zero.
	Dot is unaffected.

{{if pipeline}} T1 {{else}} T0 {{end}}
	If the value of the pipeline is empty, T0 is executed;
	otherwise, T1 is executed. Dot is unaffected.

{{if pipeline}} T1 {{else if pipeline}} T0 {{end}}
	To simplify the appearance of if-else chains, the else action
	of an if may include another if directly; the effect is exactly
	the same as writing
		{{if pipeline}} T1 {{else}}{{if pipeline}} T0 {{end}}{{end}}

{{range pipeline}} T1 {{end}}
	The value of the pipeline must be an array, slice, map, or channel.
	If the value of the pipeline has length zero, nothing is output;
	otherwise, dot is set to the successive elements of the array,
	slice, or map and T1 is executed. If the value is a map and the
	keys are of basic type with a defined order ("comparable"), the
	elements will be visited in sorted key order.

{{range pipeline}} T1 {{else}} T0 {{end}}
	The value of the pipeline must be an array, slice, map, or channel.
	If the value of the pipeline has length zero, dot is unaffected and
	T0 is executed; otherwise, dot is set to the successive elements
	of the array, slice, or map and T1 is executed.

{{template "name"}}
	The template with the specified name is executed with nil data.

{{template "name" pipeline}}
	The template with the specified name is executed with dot set
	to the value of the pipeline.

{{block "name" pipeline}} T1 {{end}}
	A block is shorthand for defining a template
		{{define "name"}} T1 {{end}}
	and then executing it in place
		{{template "name" pipeline}}
	The typical use is to define a set of root templates that are
	then customized by redefining the block templates within.

{{with pipeline}} T1 {{end}}
	If the value of the pipeline is empty, no output is generated;
	otherwise, dot is set to the value of the pipeline and T1 is
	executed.

{{with pipeline}} T1 {{else}} T0 {{end}}
	If the value of the pipeline is empty, dot is unaffected and T0
	is executed; otherwise, dot is set to the value of the pipeline
	and T1 is executed.

Arguments

参数是一个简单的值,由以下之一表示.

- A boolean, string, character, integer, floating-point, imaginary
  or complex constant in Go syntax. These behave like Go's untyped
  constants. Note that, as in Go, whether a large integer constant
  overflows when assigned or passed to a function can depend on whether
  the host machine's ints are 32 or 64 bits.
- The keyword nil, representing an untyped Go nil.
- The character '.' (period):
	.
  The result is the value of dot.
- A variable name, which is a (possibly empty) alphanumeric string
  preceded by a dollar sign, such as
	$piOver2
  or
	$
  The result is the value of the variable.
  Variables are described below.
- The name of a field of the data, which must be a struct, preceded
  by a period, such as
	.Field
  The result is the value of the field. Field invocations may be
  chained:
    .Field1.Field2
  Fields can also be evaluated on variables, including chaining:
    $x.Field1.Field2
- The name of a key of the data, which must be a map, preceded
  by a period, such as
	.Key
  The result is the map element value indexed by the key.
  Key invocations may be chained and combined with fields to any
  depth:
    .Field1.Key1.Field2.Key2
  Although the key must be an alphanumeric identifier, unlike with
  field names they do not need to start with an upper case letter.
  Keys can also be evaluated on variables, including chaining:
    $x.key1.key2
- The name of a niladic method of the data, preceded by a period,
  such as
	.Method
  The result is the value of invoking the method with dot as the
  receiver, dot.Method(). Such a method must have one return value (of
  any type) or two return values, the second of which is an error.
  If it has two and the returned error is non-nil, execution terminates
  and an error is returned to the caller as the value of Execute.
  Method invocations may be chained and combined with fields and keys
  to any depth:
    .Field1.Key1.Method1.Field2.Key2.Method2
  Methods can also be evaluated on variables, including chaining:
    $x.Method1.Field
- The name of a niladic function, such as
	fun
  The result is the value of invoking the function, fun(). The return
  types and values behave as in methods. Functions and function
  names are described below.
- A parenthesized instance of one the above, for grouping. The result
  may be accessed by a field or map key invocation.
	print (.F1 arg1) (.F2 arg2)
	(.StructValuedMethod "arg").Field

参数可以计算为任何类型; 如果它们是指针,则实现将在需要时自动间接指向基本类型. 如果求值产生函数值(例如,结构的函数值字段),则不会自动调用该函数,但可以将其用作if动作等的真值. 要调用它,请使用下面定义的调用函数.

Pipelines

管道是"命令"的可能链接的序列. 命令是简单的值(参数)或函数或方法调用,可能带有多个参数:

Argument
	The result is the value of evaluating the argument.
.Method [Argument...]
	The method can be alone or the last element of a chain but,
	unlike methods in the middle of a chain, it can take arguments.
	The result is the value of calling the method with the
	arguments:
		dot.Method(Argument1, etc.)
functionName [Argument...]
	The result is the value of calling the function associated
	with the name:
		function(Argument1, etc.)
	Functions and function names are described below.

通过使用流水线字符" |"分隔命令序列,可以"链接"流水线. 在链式管道中,每个命令的结果作为以下命令的最后一个参数传递. 流水线中最终命令的输出是流水线的值.

命令的输出将是一个值或两个值,其中第二个具有类型错误. 如果该第二个值存在并且评估为非零,则执行终止,并且错误返回给Execute的调用方.

Variables

动作内部的管道可以初始化变量以捕获结果. 初始化具有语法

$variable := pipeline

其中$ variable是变量的名称. 声明变量的操作不会产生任何输出.

也可以使用以下语法来分配先前声明的变量:

$variable = pipeline

If a "range" action initializes a variable, the variable is set to the successive elements of the iteration. Also, a "range" may declare two variables, separated by a comma:

range $index, $element := pipeline

在这种情况下,$ index和$ element分别设置为数组/切片索引或映射键和元素的连续值. 请注意,如果只有一个变量,则会为其分配元素; 这与Go range子句中的约定相反.

变量的范围扩展到声明它的控制结构(" if"," with"或" range")的"结束"动作,或者扩展到模板的末尾(如果没有这样的控制结构). 模板调用不会从调用点继承变量.

执行开始时,将$设置为传递给Execute的数据参数,即dot的起始值.

Examples

这是一些示例一线模板,展示了管道和变量. 全部产生引号"输出":

{{"\"output\""}}
	A string constant.
{{`"output"`}}
	A raw string constant.
{{printf "%q" "output"}}
	A function call.
{{"output" | printf "%q"}}
	A function call whose final argument comes from the previous
	command.
{{printf "%q" (print "out" "put")}}
	A parenthesized argument.
{{"put" | printf "%s%s" "out" | printf "%q"}}
	A more elaborate call.
{{"output" | printf "%s" | printf "%q"}}
	A longer chain.
{{with "output"}}{{printf "%q" .}}{{end}}
	A with action using dot.
{{with $x := "output" | printf "%q"}}{{$x}}{{end}}
	A with action that creates and uses a variable.
{{with $x := "output"}}{{printf "%q" $x}}{{end}}
	A with action that uses the variable in another action.
{{with $x := "output"}}{{$x | printf "%q"}}{{end}}
	The same, but pipelined.

Functions

在执行期间,在两个功能图中找到功能:首先在模板中,然后在全局功能图中. 默认情况下,模板中未定义任何函数,但可以使用Funcs方法添加它们.

预定义的全局函数命名如下.

and
	Returns the boolean AND of its arguments by returning the
	first empty argument or the last argument, that is,
	"and x y" behaves as "if x then y else x". All the
	arguments are evaluated.
call
	Returns the result of calling the first argument, which
	must be a function, with the remaining arguments as parameters.
	Thus "call .X.Y 1 2" is, in Go notation, dot.X.Y(1, 2) where
	Y is a func-valued field, map entry, or the like.
	The first argument must be the result of an evaluation
	that yields a value of function type (as distinct from
	a predefined function such as print). The function must
	return either one or two result values, the second of which
	is of type error. If the arguments don't match the function
	or the returned error value is non-nil, execution stops.
html
	Returns the escaped HTML equivalent of the textual
	representation of its arguments. This function is unavailable
	in html/template, with a few exceptions.
index
	Returns the result of indexing its first argument by the
	following arguments. Thus "index x 1 2 3" is, in Go syntax,
	x[1][2][3]. Each indexed item must be a map, slice, or array.
slice
	slice returns the result of slicing its first argument by the
	remaining arguments. Thus "slice x 1 2" is, in Go syntax, x[1:2],
	while "slice x" is x[:], "slice x 1" is x[1:], and "slice x 1 2 3"
	is x[1:2:3]. The first argument must be a string, slice, or array.
js
	Returns the escaped JavaScript equivalent of the textual
	representation of its arguments.
len
	Returns the integer length of its argument.
not
	Returns the boolean negation of its single argument.
or
	Returns the boolean OR of its arguments by returning the
	first non-empty argument or the last argument, that is,
	"or x y" behaves as "if x then x else y". All the
	arguments are evaluated.
print
	An alias for fmt.Sprint
printf
	An alias for fmt.Sprintf
println
	An alias for fmt.Sprintln
urlquery
	Returns the escaped value of the textual representation of
	its arguments in a form suitable for embedding in a URL query.
	This function is unavailable in html/template, with a few
	exceptions.

布尔函数将任何零值设为false,将非零值设为true.

还有一组二进制比较运算符定义为函数:

eq
	Returns the boolean truth of arg1 == arg2
ne
	Returns the boolean truth of arg1 != arg2
lt
	Returns the boolean truth of arg1 < arg2
le
	Returns the boolean truth of arg1 <= arg2
gt
	Returns the boolean truth of arg1 > arg2
ge
	Returns the boolean truth of arg1 >= arg2

对于更简单的多路相等性测试,eq(仅)接受两个或多个参数,并比较第二个参数和第一个参数之后的参数,并返回有效值

arg1==arg2 || arg1==arg3 || arg1==arg4 ...

(但是,与Go中的||不同,eq是一个函数调用,所有参数都将被求值.)

比较功能仅适用于基本类型(或命名的基本类型,例如" Celsius float32类型"). 它们执行Go规则以比较值,只是忽略大小和精确类型,因此可以将任何带符号或无符号的整数值与任何其他整数值进行比较. (比较算术值而不是位模式,因此所有负整数都小于所有无符号整数.)但是,像往常一样,可能无法将int与float32进行比较,依此类推.

Associated templates

每个模板均由创建时指定的字符串命名. 此外,每个模板都与零个或多个其他可以通过名称调用的模板相关联; 这样的关联是可传递的,并形成模板的名称空间.

模板可以使用模板调用来实例化另一个关联的模板. 请参阅上面对"模板"操作的说明. 该名称必须是与包含调用的模板关联的模板的名称.

Nested template definitions

解析模板时,可以定义另一个模板并将其与要解析的模板关联. 模板定义必须出现在模板的顶层,就像Go程序中的全局变量一样.

这种定义的语法是用"定义"和"结束"动作来包围每个模板声明.

定义动作通过提供字符串常量来命名正在创建的模板. 这是一个简单的示例:

`{{define "T1"}}ONE{{end}}
{{define "T2"}}TWO{{end}}
{{define "T3"}}{{template "T1"}} {{template "T2"}}{{end}}
{{template "T3"}}`

这定义了两个模板T1和T2,以及第三个模板T3,该模板在执行时调用其他两个模板. 最后,它调用T3. 如果执行此模板将产生文本

ONE TWO

通过构造,模板可以仅驻留在一个关联中. 如果需要一个可从多个关联中寻址的模板,则必须多次分析模板定义以创建不同的* Template值,或者必须使用Clone或AddParseTree方法将其复制.

可以多次调用parse来组装各种相关模板. 有关解析存储在文件中的相关模板的简单方法,请参见ParseFiles和ParseGlob函数和方法.

可以直接执行模板,也可以通过ExecuteTemplate执行模板,该模板执行由名称标识的关联模板. 为了调用上面的示例,我们可以这样写:

err := tmpl.Execute(os.Stdout, "no data needed")
if err != nil {
	log.Fatalf("execution failed: %s", err)
}

或通过名称显式调用特定模板,

err := tmpl.ExecuteTemplate(os.Stdout, "T2", "no data needed")
if err != nil {
	log.Fatalf("execution failed: %s", err)
}

Index ▾

func HTMLEscape(w io.Writer, b []byte)
func HTMLEscapeString(s string) string
func HTMLEscaper(args ...interface{}) string
func IsTrue(val interface{}) (truth, ok bool)
func JSEscape(w io.Writer, b []byte)
func JSEscapeString(s string) string
func JSEscaper(args ...interface{}) string
func URLQueryEscaper(args ...interface{}) string
type ExecError
    func (e ExecError) Error() string
    func (e ExecError) Unwrap() error
type FuncMap
type Template
    func Must(t *Template, err error) *Template
    func New(name string) *Template
    func ParseFiles(filenames ...string) (*Template, error)
    func ParseGlob(pattern string) (*Template, error)
    func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)
    func (t *Template) Clone() (*Template, error)
    func (t *Template) DefinedTemplates() string
    func (t *Template) Delims(left, right string) *Template
    func (t *Template) Execute(wr io.Writer, data interface{}) error
    func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error
    func (t *Template) Funcs(funcMap FuncMap) *Template
    func (t *Template) Lookup(name string) *Template
    func (t *Template) Name() string
    func (t *Template) New(name string) *Template
    func (t *Template) Option(opt ...string) *Template
    func (t *Template) Parse(text string) (*Template, error)
    func (t *Template) ParseFiles(filenames ...string) (*Template, error)
    func (t *Template) ParseGlob(pattern string) (*Template, error)
    func (t *Template) Templates() []*Template

Package files

doc.go exec.go funcs.go helper.go option.go template.go

func HTMLEscape

func HTMLEscape(w io.Writer, b []byte)

HTMLEscape将等同于纯文本数据b的转义HTML写入w.

func HTMLEscapeString

func HTMLEscapeString(s string) string

HTMLEscapeString返回等效于纯文本数据s的转义HTML.

func HTMLEscaper

func HTMLEscaper(args ...interface{}) string

HTMLEscaper返回与其参数的文本表示形式等效的转义HTML.

func IsTrue 1.6

func IsTrue(val interface{}) (truth, ok bool)

IsTrue报告值是否为" true"(不是其类型的零),以及该值是否具有有意义的真值. 这是if和其他此类操作使用的真相定义.

func JSEscape

func JSEscape(w io.Writer, b []byte)

JSEscape将等同于纯文本数据b的转义JavaScript写入w.

func JSEscapeString

func JSEscapeString(s string) string

JSEscapeString返回等效于纯文本数据s的转义JavaScript.

func JSEscaper

func JSEscaper(args ...interface{}) string

JSEscaper返回等效于其参数的文本表示形式的转义JavaScript.

func URLQueryEscaper

func URLQueryEscaper(args ...interface{}) string

URLQueryEscaper以适合嵌入URL查询的形式返回其参数的文本表示形式的转义值.

type ExecError 1.6

ExecError是Execute在评估其模板时发生错误时返回的自定义错误类型. (如果发生写错误,则返回实际错误;它不会属于ExecError类型.)

type ExecError struct {
    Name string // Name of template.
    Err  error  // Pre-formatted error.
}

func (ExecError) Error 1.6

func (e ExecError) Error() string

func (ExecError) Unwrap 1.13

func (e ExecError) Unwrap() error

type FuncMap

FuncMap是定义从名称到函数的映射的映射类型. 每个函数必须具有单个返回值,或者具有两个返回值,其中第二个具有类型错误. 在这种情况下,如果第二个(错误)返回值在执行过程中评估为非零,则执行终止,并且Execute返回该错误.

当模板执行调用带有参数列表的函数时,该列表必须可分配给函数的参数类型. 适用于任意类型参数的函数可以使用interface {}类型或reflect.Value类型的参数. 同样,旨在返回任意类型结果的函数可以返回interface {}或reflect.Value.

type FuncMap map[string]interface{}

type Template

模板是已解析模板的表示. * parse.Tree字段仅导出供html / template使用,并且应被所有其他客户端视为未导出.

type Template struct {
    *parse.Tree
    // contains filtered or unexported fields
}

Example

Dear Aunt Mildred,

It was a pleasure to see you at the wedding.
Thank you for the lovely bone china tea set.

Best wishes,
Josie

Dear Uncle John,

It is a shame you couldn't make it to the wedding.
Thank you for the lovely moleskin pants.

Best wishes,
Josie

Dear Cousin Rodney,

It is a shame you couldn't make it to the wedding.

Best wishes,
Josie

示例(块)

Names:
- Gamora
- Groot
- Nebula
- Rocket
- Star-Lord
Names: Gamora, Groot, Nebula, Rocket, Star-Lord

示例(功能)

本示例演示了用于处理模板文本的自定义函数. 它安装strings.Title函数,并使用它使标题文本在模板的输出中看起来不错.

Input: "the go programming language"
Output 0: The Go Programming Language
Output 1: "The Go Programming Language"
Output 2: "The Go Programming Language"

示例(全局)

在这里,我们演示了从目录加载一组模板.

T0 invokes T1: (T1 invokes T2: (This is T2))

示例(助手)

此示例演示了一种共享模板并在不同上下文中使用它们的方法. 在此变体中,我们将多个驱动程序模板手动添加到现有的模板包中.

Driver 1 calls T1: (T1 invokes T2: (This is T2))
Driver 2 calls T2: (This is T2)

示例(分享)

本示例演示如何将一组驱动程序模板与不同的帮助程序模板集一起使用.

T0 (second version) invokes T1: (T1 invokes T2: (T2, version B))
T0 (first version) invokes T1: (T1 invokes T2: (T2, version A))

func Must

func Must(t *Template, err error) *Template

Must是一个帮助程序,它包装对返回的函数的调用(* Template,错误),如果错误为非nil,则会出现恐慌. 它旨在用于变量初始化,例如

var t = template.Must(template.New("name").Parse("text"))

func New

func New(name string) *Template

New使用给定名称分配新的未定义模板.

func ParseFiles

func ParseFiles(filenames ...string) (*Template, error)

ParseFiles创建一个新的模板,并从命名文件中解析模板定义. 返回的模板名称将具有第一个文件的基本名称和已解析的内容. 必须至少有一个文件. 如果发生错误,解析将停止并且返回的* Template为nil.

当在不同目录中解析具有相同名称的多个文件时,最后提到的将是结果文件. 例如,ParseFiles(" a / foo"," b / foo")将" b / foo"存储为名为" foo"的模板,而" a / foo"不可用.

func ParseGlob

func ParseGlob(pattern string) (*Template, error)

ParseGlob创建一个新的模板,并从该模式标识的文件中解析模板定义. 这些文件根据filepath.Match的语义进行匹配,并且该模式必须匹配至少一个文件. 返回的模板将具有与模式匹配的第一个文件的(基本)名称和(解析的)内容. ParseGlob等效于使用模式匹配的文件列表调用ParseFiles.

当在不同目录中解析具有相同名称的多个文件时,最后提到的将是结果文件.

func (*Template) AddParseTree

func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)

AddParseTree为具有给定名称的模板添加解析树,并将其与t关联. 如果该模板尚不存在,它将创建一个新模板. 如果模板确实存在,它将被替换.

func (*Template) Clone

func (t *Template) Clone() (*Template, error)

克隆返回模板的副本,包括所有关联的模板. 不会复制实际的表示形式,但是会复制关联模板的名称空间,因此在副本中进一步调用Parse会将模板添加到副本中,而不是原始模板. 克隆可用于准备通用模板,并将其与其他模板的变体定义一起使用,方法是在克隆完成后添加变体.

func (*Template) DefinedTemplates 1.5

func (t *Template) DefinedTemplates() string

DefinedTemplates返回一个字符串,该字符串列出了已定义的模板,并以字符串";"作为前缀. 如果没有,则返回空字符串. 用于在此处和html / template中生成错误消息.

func (*Template) Delims

func (t *Template) Delims(left, right string) *Template

Delims将动作定界符设置为指定的字符串,以在后续对Parse,ParseFiles或ParseGlob的调用中使用. 嵌套模板定义将继承设置. 空分隔符代表相应的默认值:{{或}}. 返回值是模板,因此可以链接调用.

func (*Template) Execute

func (t *Template) Execute(wr io.Writer, data interface{}) error

Execute将已解析的模板应用于指定的数据对象,并将输出写入wr. 如果执行模板或写入其输出时发生错误,则执行将停止,但是可能已将部分结果写入输出写入器. 模板可以安全地并行执行,尽管如果并行执行共享一个Writer,则输出可能会交错.

如果数据是reflect.Value,则该模板将应用于reflect.Value所持有的具体值,如fmt.Print中所示.

func (*Template) ExecuteTemplate

func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error

ExecuteTemplate将与具有给定名称的t关联的模板应用于指定的数据对象,并将输出写入wr. 如果执行模板或写入其输出时发生错误,则执行将停止,但是可能已将部分结果写入输出写入器. 模板可以安全地并行执行,尽管如果并行执行共享一个Writer,则输出可能会交错.

func (*Template) Funcs

func (t *Template) Funcs(funcMap FuncMap) *Template

Funcs将参数映射的元素添加到模板的功能映射. 必须在解析模板之前调用它. 如果映射中的值不是具有适当返回类型的函数,或者该名称不能在语法上用作模板中的函数,则它会感到恐慌. 覆盖地图元素是合法的. 返回值是模板,因此可以链接调用.

func (*Template) Lookup

func (t *Template) Lookup(name string) *Template

查找将返回具有与t关联的给定名称的模板. 如果没有这样的模板或模板没有定义,则返回nil.

func (*Template) Name

func (t *Template) Name() string

名称返回模板的名称.

func (*Template) New

func (t *Template) New(name string) *Template

New分配与给定模板和相同定界符关联的未定义的新模板. 该关联是可传递的,它允许一个模板使用{{template}}动作来调用另一个模板.

由于关联的模板共享基础数据,因此无法安全并行地进行模板构建. 模板一旦构建,就可以并行执行.

func (*Template) Option 1.5

func (t *Template) Option(opt ...string) *Template

选项设置模板的选项. 选项由字符串(简单字符串或"键=值")描述. 选项字符串中最多可以有一个等号. 如果选项字符串无法识别或无效,则选项会出现紧急情况.

已知选项:

missingkey:如果使用映射中不存在的键索引了映射,则控制执行期间的行为.

"missingkey=default" or "missingkey=invalid"
	The default behavior: Do nothing and continue execution.
	If printed, the result of the index operation is the string
	"<no value>".
"missingkey=zero"
	The operation returns the zero value for the map type's element.
"missingkey=error"
	Execution stops immediately with an error.

func (*Template) Parse

func (t *Template) Parse(text string) (*Template, error)

解析将文本解析为t的模板主体. 文本中的命名模板定义({{define ...}}或{{block ...}}语句)定义了与t关联的其他模板,并从t本身的定义中删除.

可以在连续调用Parse中重新定义模板. 具有仅包含空白和注释的主体的模板定义被认为是空的,不会替换现有模板的主体. 这允许使用Parse添加新的命名模板定义,而不会覆盖主模板主体.

func (*Template) ParseFiles

func (t *Template) ParseFiles(filenames ...string) (*Template, error)

ParseFiles解析命名的文件,并将生成的模板与t关联. 如果发生错误,则分析停止,返回的模板为nil; 否则为t. 必须至少有一个文件. 由于由ParseFiles创建的模板由参数文件的基本名称命名,因此t通常应具有文件(基本)名称之一的名称. 如果不是,则根据t的内容,在调用ParseFiles之前,t.Execute可能会失败. 在这种情况下,请使用t.ExecuteTemplate执行有效的模板.

当在不同目录中解析具有相同名称的多个文件时,最后提到的将是结果文件.

func (*Template) ParseGlob

func (t *Template) ParseGlob(pattern string) (*Template, error)

ParseGlob解析由模式标识的文件中的模板定义,并将结果模板与t关联. 这些文件根据filepath.Match的语义进行匹配,并且该模式必须匹配至少一个文件. ParseGlob等效于使用模式匹配的文件列表调用t.ParseFiles.

当在不同目录中解析具有相同名称的多个文件时,最后提到的将是结果文件.

func (*Template) Templates

func (t *Template) Templates() []*Template

模板返回与t关联的已定义模板的切片.

Subdirectories

Name Synopsis
..
parse Package parse builds parse trees for templates as defined by text/template and html/template.

by  ICOPY.SITE