Package template
templateパッケージはテキストの出力を生成するデータ駆動テンプレートを実装します。
HTMLの出力を生成するには、html/templateパッケージを参照してください。
html/templateパッケージはこのパッケージと同じインタフェースを備えていますが、
HTML出力を既知の攻撃から自動的に守ります。
テンプレートはデータ構造へ適用することで実行されます。
テンプレート中のアノテーションはデータ構造内の要素(典型的には構造体のフィールド、またはマップのキー)を参照し、実行の制御や値の表示を行います。
テンプレートの実行はデータ構造内を移動し、実行の進捗を示すために、データ構造内の現在地を示す値にカーソルをセットします。
カーソルは1つのピリオド'.'で表され、「ドット」と呼ばれます。
テンプレートへの入力テキストはフォーマットなしのUTF-8でエンコードされたテキストです。
データ評価または制御構造である「アクション」は"{{"と"}}"で区切られます。
アクションの外側のテキストは全てそのまま出力となります。
アクションは改行はできませんが、コメントは可能です。
一度パースされると、テンプレートは安全に並行して実行できるようになります。
以下は"17 items are made of wool"と表示する簡単な例です。
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) }
この先にはより複雑な例があります。
Actions
以下はアクションのリストです。
データの評価を行う「引数」と「パイプライン」についてはその後で詳細な説明をします。
{{/* a comment */}}
コメント: 破棄されます。改行を含むことができます。
コメントはネストできず、ここで示している区切り文字で開始・終了する必要があります。
{{pipeline}}
pipelineの値に対するデフォルトのテキスト表現が出力されます。
{{if pipeline}} T1 {{end}}
pipelineの値が空の場合、何も出力されません。
そうでない場合、T1が実行されます。
空の値とは、false、0、nilポインタまたはインタフェース値、
長さがゼロの配列、スライス、マップ、文字列です。
ドットは影響を受けません。
{{if pipeline}} T1 {{else}} T0 {{end}}
pipelineの値が空の場合、T0が実行されます。
そうでない場合、T1が実行されます。
ドットは影響を受けません。
{{if pipeline}} T1 {{else if pipeline}} T0 {{end}}
if-elseの連鎖が起きないように、elseアクションは他のifを直接含めることができます。
この例は次の文とまったく同じ意味になります。
{{if pipeline}} T1 {{else}}{{if pipeline}} T0 {{end}}{{end}}
{{range pipeline}} T1 {{end}}
pipelineの値は配列、スライス、マップ、チャネルのどれかである必要があります。
pipelineの値の長さがゼロの場合、何も出力されません。
そうでない場合、配列、スライス、マップ中の次の要素にドットがセットされ、T1が実行されます。
値がマップで、キーが整列可能である(「比較可能」である)基本型の値である場合、
要素はキーがソートされた順にアクセスされます。
{{range pipeline}} T1 {{else}} T0 {{end}}
pipelineの値は配列、スライス、マップ、チャネルのどれかである必要があります。
pipelineの値の長さがゼロの場合、ドットは影響を受けず、T0が実行されます。
そうでない場合、配列、スライス、マップ中の次の要素にドットがセットされ、T1が実行されます。
{{template "name"}}
指定された名前のテンプレートがnilデータに対して実行されます。
{{template "name" pipeline}}
ドットがpipelineの値にセットされ、指定された名前のテンプレートが実行されます。
{{with pipeline}} T1 {{end}}
pipelineの値が空の場合、出力は何も生成されません。
そうでない場合、ドットがpipelineの値にセットされ、T1が実行されます。
{{with pipeline}} T1 {{else}} T0 {{end}}
pipelineの値が空の場合、ドットは影響を受けず、T0が実行されます。
そうでない場合、ドットがpipelineの値にセットされ、T1が実行されます。
Arguments
引数は以下に示されるような単純な値です。
- Goの文法における真偽値、文字列、文字、数値、浮動小数点数、虚数、複素数の定数。
これらはGoの型指定なしの定数と同じように振る舞いますが、未加工文字列中の改行は無視されます。
- nil値。Goの型指定なしのnilと同じです。
- ピリオド文字'.':
.
結果はドットの値です。
- 変数名。ドルマークに続く英数字の文字列(なくてもよい)です。例えば以下のようなものです。
$piOver2
あるいは以下のようなものです。
$
結果は変数の値です。
変数については後で説明します。
- 構造体のフィールドの名前。以下のように、前にピリオドを付けます。
.Field
結果はフィールドの値です。フィールドは連鎖させることができます:
.Field1.Field2
フィールドは変数から連鎖させて評価させることもできます:
.$x.Field1.Field2
- マップのキーの名前。以下のように、前にピリオドを付けます。
.Key
結果はマップ中のそのキーに対応した要素の値です。
キーはフィールドと組み合わせて何段も連鎖させることができます:
.Field1.Key1.Field2.Key2
キーは英数字の名前でなくてはなりませんが、フィールド名のように大文字で始まる必要がありません。
キーは変数から連鎖させて評価させることもできます:
$x.key1.key2
- 引数なしのメソッド。以下のように、前にピリオドを付けます。
.Method
結果はドットをレシーバとしてドット.Method()を実行した結果になります。
このようなメソッドは任意の型の戻り値1つか、第2戻り値としてerrorを加えた2つの戻り値を返す必要があります。
戻り値が2つでerrorが非nilであれば、実行結果はエラーとなります。
メソッドの呼び出しはフィールドやキーと組み合わせて何段も連鎖させることができます:
.Field1.Key1.Method1.Field2.Key2.Method2
メソッドは変数から連鎖させて評価させることもできます"
$x.Method1.Field
- 引数なしの関数。以下のようなものです。
fun
結果は関数fun()を実行した結果になります。
返される型と値はメソッドの場合と同じ振る舞いです。
関数と関数名は後で説明します。
- ここまでに説明したものは丸括弧で囲むとグループになります。
結果はフィールドまたはマップのキー呼び出しによってアクセスできます。
print (.F1 arg1) (.F2 arg2)
(.StructValuedMethod "arg").Field
引数は任意の型になります。引数がポインタであれば、必要に応じて値型になります。
構造体の関数型フィールドのように、評価によって関数値が生成される場合、その関数は自動的には実行されませんが、ifアクションなどにとってはtrueとして扱われます。
関数を実行する方法は、以降で示しています。
パイプラインは可能な限り「コマンド」のシーケンスをつないだものになります。
コマンドは単なる値(引数)か、可能な限り複数の引数をとるようにした関数またはメソッドです。
Argument
結果は引数の評価値です。
.Method [Argument...]
メソッドは単独か連鎖の最後の要素ですが、連鎖の中間にあるメソッドと違い、引数をとることができます。
結果は引数を与えてメソッドを実行した結果になります:
dot.Method(Argument1, etc.)
functionName [Argument...]
結果はその名前に紐付いている関数を実行した値になります:
function(Argument1, etc.)
関数と関数名については以降で示します。
Pipelines
パイプラインはパイプライン文字'|'で区切ってコマンドをつなげることによって「連鎖」させることができます。
連鎖されたパイプラインでは、各コマンドの結果は次のコマンドへ最後の引数として渡されます。
パイプラインにおける最後のコマンドの出力がそのパイプラインの値になります。
コマンドの出力が1つか2つの場合、2番目の出力はerror型になります。
もし2つめの値が存在し、評価結果がnilでなければ、実行は終了し、呼び出し元へはエラーが返されます。
Variables
アクション内のパイプラインは変数を初期化し結果を受け取ることができます。
初期化の構文は次の通りです。
$variable := pipeline
$variableは変数の名前です。
変数を宣言するアクションは何も出力しません。
"range"アクションが変数を初期化する場合、変数にはイテレーションで毎回生成される値がセットされます。
"range"がカンマで区切った2つの変数を宣言する場合:
range $index, $element := pipeline
この場合、$indexと$elementは、毎回生成される、配列・スライスのインデックスあるいはマップのキーと値がそれぞれセットされます。
1つだけ変数がある場合は、値がセットされることに注意してください。これはGoのrange式と同様になっています。
変数のスコープはそれが宣言された制御構造("if", "with", "range")における"end"アクションまで続きます。
制御構造がない場合はテンプレートの終わりまで続きます。
テンプレートは実行された箇所から変数を受け継ぐことはありません。
実行が始まった時、$は実行に渡されたデータ引数にセットされます。
つまり最初の値はドットであるということです。
Examples
以下はパイプラインと変数をデモする1行テンプレートの例です。
これら全てがダブルクオートで囲まれた"output"という語を出力します。
{{"\"output\""}}
文字列定数です。
{{`"output"`}}
未加工文字列定数です。
{{printf "%q" "output"}}
関数呼び出しです。
{{"output" | printf "%q"}}
関数呼び出しですが、最後の引数は前のコマンドから受け取っています。
{{printf "%q" (print "out" "put")}}
カッコで囲まれた引数です。
{{"put" | printf "%s%s" "out" | printf "%q"}}
より複雑な関数呼び出しです。
{{"output" | printf "%s" | printf "%q"}}
少し長い連鎖です。
{{with "output"}}{{printf "%q" .}}{{end}}
ドットを使ったアクションの例です。
{{with $x := "output" | printf "%q"}}{{$x}}{{end}}
変数を生成して使用するアクションの例です。
{{with $x := "output"}}{{printf "%q" $x}}{{end}}
別のアクションで変数を利用する例です。
{{with $x := "output"}}{{$x | printf "%q"}}{{end}}
同様の例ですが、パイプラインを使っています。
Functions
実行の間、関数は次の2つの関数マップから探されます:
1つめはテンプレート中にあるもので、その場合はグローバルな関数マップになります。
デフォルトではテンプレート内で関数は定義されていませんが、Funcsメソッドによって関数を追加することができます。
あらかじめ定義されたグローバル関数は次のようになっています。
and
引数のAND値を返します。最初の空の引数または最後の引数を返します。
つまり、"and x y"は「xが真のときy、そうでなければx」となります。
全ての引数は評価されます。
call
最初の引数の関数に残りの引数をパラメータとして与えて実行した結果を返します。
例えば"call .X.Y 1 2"はGoで書くと dot.X.Y(1, 2) となります。Yは関数型のフィールドやマップのエントリ等です。
最初の引数は関数型の値(printのような組み込み関数ではないもの)を生成する評価結果でなくてはなりません。
関数は1つまたは2つの値を返す必要があり、2番目はerror型になります。
引数が関数型でない、あるいは戻り値のerror値がnilでなかった場合、実行は停止します。
html
引数のテキスト表現をエスケープされたHTMLに変換したものを返します。
index
最初の引数を続く引数でインデックスした結果を返します。
例えば"index x 1 2 3"はGoの文法では x[1][2][3]となります。
インデックスされる値はマップ、スライス、配列である必要があります。
js
引数のテキスト表現をエスケープされたJavaScriptに変換したものを返します。
len
引数の長さを表す整数を返します。
not
引数を1つ受け取り、その論理否定値を返します。
or
引数のOR値を返します。最初の空の引数または最後の引数を返します。
つまり、"or x y"は「xが真のときx、そうでなければy」となります。
全ての引数は評価されます。
print
fmt.Sprintへのエイリアスです。
printf
fmt.Sprintfへのエイリアスです。
println
fmt.Sprintlnへのエイリアスです。
urlquery
引数のテキスト表現を、URLのクエリとして埋め込み可能な形式に変換して返します。
真偽値の関数はゼロ値を受け取るとfalseを、非ゼロ値を受け取るとtrueを返します。
以下のような二項比較演算子の関数もあります:
eq
arg1 == arg2ならば真を返します。
ne
arg1 != arg2ならば真を返します。
lt
arg1 < arg2ならば真を返します。
le
arg1 <= arg2ならば真を返します。
gt
arg1 > arg2ならば真を返します。
ge
arg1 >= arg2ならば真を返します。
単純な複数比較のテストでは、eq(だけ)は2つ以上の引数を取り、2番目やそれ以降の引数を最初の引数と比較します。
要するに以下のような結果を返します。
arg1==arg2 || arg1==arg3 || arg1==arg4 ...
(Goの||と異なり、eqは関数呼び出しであり、全ての引数は評価されます。)
比較関数は基本型(または"type Celsius float32"のように名前を付けた基本型)にのみ有効です。
これらはGoにおける値の比較を実装していますが、値のサイズと厳密な型は無視されます。
よってあらゆる整数値同士や符号なし整数値同士などを比較することができます。
しかしやはり、intとfloat32との比較のようなことはできません。
Associated templates
各テンプレートは生成されるときに指定された文字列の名前が付きます。
また、各テンプレートは名前によって自分が起動した0個以上の他のテンプレートへ関連付けられます。
このような関連付けは推移的であり、テンプレートの名前空間を形成します。
テンプレートは他の関連付けられたテンプレートを起動することによってインスタンス化することができます。
前述の"template"アクションの説明を見てください。
名前は起動を行うテンプレートと関連付けられたテンプレートのものである必要があります。
Nested template definitions
テンプレートをパースするとき、他のテンプレートを定義し、パース中のテンプレートと関連付けることができます。
テンプレートの定義はGoのプログラムにおけるグローバル変数のようにテンプレートのトップレベルに存在しなければなりません。
このような定義の文法は、それぞれのテンプレートの宣言を"define"と"end"で囲みます。
defineアクションは生成されるテンプレートに文字列定数を使って名前付けをします。
以下は簡単な例です:
`{{define "T1"}}ONE{{end}}
{{define "T2"}}TWO{{end}}
{{define "T3"}}{{template "T1"}} {{template "T2"}}{{end}}
{{template "T3"}}`
これはT1とT2の2つのテンプレートを定義します。
そして3つめのT3は他の2つを実行するものです。
最後にT3を起動します。
実行するとこのテンプレートは以下のテキストを生成します。
ONE TWO
組み立てられたテンプレートは1つだけ関連付けに属することができます。
複数の関連付けから辿れるようにする必要がある場合、テンプレートの定義は個々の*Template型の値を生成するために複数回パースされる必要があります。
あるいは、CloneかAddParseTreeメソッドを使ってコピーされる必要があります。
パースは関連付けられた個々のテンプレートを組み立てるために複数回実行されます。
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)
}
本ドキュメントは以下のドキュメントを翻訳しています: https://code.google.com/p/go/source/browse/src/pkg/text/template/doc.go?r=ae48c492cd8d2f2d5c3b728345882a31a085dfcd
- func HTMLEscape(w io.Writer, b []byte)
- func HTMLEscapeString(s string) string
- func HTMLEscaper(args ...interface{}) string
- func JSEscape(w io.Writer, b []byte)
- func JSEscapeString(s string) string
- func JSEscaper(args ...interface{}) string
- func URLQueryEscaper(args ...interface{}) string
- 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) Delims(left, right string) *Template
- func (t *Template) Execute(wr io.Writer, data interface{}) (err 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) 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
template.go
In the call graph viewer below, each node
is a function belonging to this package
and its children are the functions it
calls—perhaps dynamically.
The root nodes are the entry points of the
package: functions that may be called from
outside the package.
There may be non-exported or anonymous
functions among them if they are called
dynamically from another package.
Click a node to visit that function's source code.
From there you can visit its callers by
clicking its declaring func
token.
Functions may be omitted if they were
determined to be unreachable in the
particular programs or tests that were
analyzed.
func HTMLEscape(w io.Writer, b []byte)
HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.
func HTMLEscapeString(s string) string
HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.
func HTMLEscaper(args ...interface{}) string
HTMLEscaper returns the escaped HTML equivalent of the textual
representation of its arguments.
func JSEscape(w io.Writer, b []byte)
JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.
func JSEscapeString(s string) string
JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.
func JSEscaper(args ...interface{}) string
JSEscaper returns the escaped JavaScript equivalent of the textual
representation of its arguments.
func URLQueryEscaper(args ...interface{}) string
URLQueryEscaper returns the escaped value of the textual representation of
its arguments in a form suitable for embedding in a URL query.
type FuncMap map[string]interface{}
FuncMap is the type of the map defining the mapping from names to functions.
Each function must have either a single return value, or two return values of
which the second has type error. In that case, if the second (error)
return value evaluates to non-nil during execution, execution terminates and
Execute returns that error.
type Template struct {
*parse.Tree
}
Template is the representation of a parsed template. The *parse.Tree
field is exported only for use by html/template and should be treated
as unexported by all other clients.
▾ 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
▾ Example (Func)
This example demonstrates a custom function to process template text.
It installs the strings.Title function and uses it to
Make Title Text Look Good In Our Template's Output.
Input: "the go programming language"
Output 0: The Go Programming Language
Output 1: "The Go Programming Language"
Output 2: "The Go Programming Language"
▾ Example (Glob)
Here we demonstrate loading a set of templates from a directory.
Code:
dir := createTestDir([]templateFile{
{"T0.tmpl", `T0 invokes T1: ({{template "T1"}})`},
{"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
{"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
})
defer os.RemoveAll(dir)
pattern := filepath.Join(dir, "*.tmpl")
tmpl := template.Must(template.ParseGlob(pattern))
err := tmpl.Execute(os.Stdout, nil)
if err != nil {
log.Fatalf("template execution: %s", err)
}
Output:
T0 invokes T1: (T1 invokes T2: (This is T2))
▾ Example (Helpers)
This example demonstrates one way to share some templates
and use them in different contexts. In this variant we add multiple driver
templates by hand to an existing bundle of templates.
Code:
dir := createTestDir([]templateFile{
{"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
{"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},
})
defer os.RemoveAll(dir)
pattern := filepath.Join(dir, "*.tmpl")
templates := template.Must(template.ParseGlob(pattern))
_, err := templates.Parse("{{define `driver1`}}Driver 1 calls T1: ({{template `T1`}})\n{{end}}")
if err != nil {
log.Fatal("parsing driver1: ", err)
}
_, err = templates.Parse("{{define `driver2`}}Driver 2 calls T2: ({{template `T2`}})\n{{end}}")
if err != nil {
log.Fatal("parsing driver2: ", err)
}
err = templates.ExecuteTemplate(os.Stdout, "driver1", nil)
if err != nil {
log.Fatalf("driver1 execution: %s", err)
}
err = templates.ExecuteTemplate(os.Stdout, "driver2", nil)
if err != nil {
log.Fatalf("driver2 execution: %s", err)
}
Output:
Driver 1 calls T1: (T1 invokes T2: (This is T2))
Driver 2 calls T2: (This is T2)
▾ Example (Share)
This example demonstrates how to use one group of driver
templates with distinct sets of helper templates.
Code:
dir := createTestDir([]templateFile{
{"T0.tmpl", "T0 ({{.}} version) invokes T1: ({{template `T1`}})\n"},
{"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},
})
defer os.RemoveAll(dir)
pattern := filepath.Join(dir, "*.tmpl")
drivers := template.Must(template.ParseGlob(pattern))
first, err := drivers.Clone()
if err != nil {
log.Fatal("cloning helpers: ", err)
}
_, err = first.Parse("{{define `T2`}}T2, version A{{end}}")
if err != nil {
log.Fatal("parsing T2: ", err)
}
second, err := drivers.Clone()
if err != nil {
log.Fatal("cloning drivers: ", err)
}
_, err = second.Parse("{{define `T2`}}T2, version B{{end}}")
if err != nil {
log.Fatal("parsing T2: ", err)
}
err = second.ExecuteTemplate(os.Stdout, "T0.tmpl", "second")
if err != nil {
log.Fatalf("second execution: %s", err)
}
err = first.ExecuteTemplate(os.Stdout, "T0.tmpl", "first")
if err != nil {
log.Fatalf("first: execution: %s", err)
}
Output:
T0 (second version) invokes T1: (T1 invokes T2: (T2, version B))
T0 (first version) invokes T1: (T1 invokes T2: (T2, version A))
func Must(t *Template, err error) *Template
Must is a helper that wraps a call to a function returning (*Template, error)
and panics if the error is non-nil. It is intended for use in variable
initializations such as
var t = template.Must(template.New("name").Parse("text"))
func New(name string) *Template
New allocates a new template with the given name.
func ParseFiles(filenames ...string) (*Template, error)
ParseFiles creates a new Template and parses the template definitions from
the named files. The returned template's name will have the (base) name and
(parsed) contents of the first file. There must be at least one file.
If an error occurs, parsing stops and the returned *Template is nil.
func ParseGlob(pattern string) (*Template, error)
ParseGlob creates a new Template and parses the template definitions from the
files identified by the pattern, which must match at least one file. The
returned template will have the (base) name and (parsed) contents of the
first file matched by the pattern. ParseGlob is equivalent to calling
ParseFiles with the list of files matched by the pattern.
func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)
AddParseTree creates a new template with the name and parse tree
and associates it with t.
func (*Template) Clone
func (t *Template) Clone() (*Template, error)
Clone returns a duplicate of the template, including all associated
templates. The actual representation is not copied, but the name space of
associated templates is, so further calls to Parse in the copy will add
templates to the copy but not to the original. Clone can be used to prepare
common templates and use them with variant definitions for other templates
by adding the variants after the clone is made.
func (*Template) Delims
func (t *Template) Delims(left, right string) *Template
Delims sets the action delimiters to the specified strings, to be used in
subsequent calls to Parse, ParseFiles, or ParseGlob. Nested template
definitions will inherit the settings. An empty delimiter stands for the
corresponding default: {{ or }}.
The return value is the template, so calls can be chained.
func (*Template) Execute
func (t *Template) Execute(wr io.Writer, data interface{}) (err error)
Execute applies a parsed template to the specified data object,
and writes the output to wr.
If an error occurs executing the template or writing its output,
execution stops, but partial results may already have been written to
the output writer.
A template may be executed safely in parallel.
func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error
ExecuteTemplate applies the template associated with t that has the given name
to the specified data object and writes the output to wr.
If an error occurs executing the template or writing its output,
execution stops, but partial results may already have been written to
the output writer.
A template may be executed safely in parallel.
func (*Template) Funcs
func (t *Template) Funcs(funcMap FuncMap) *Template
Funcs adds the elements of the argument map to the template's function map.
It panics if a value in the map is not a function with appropriate return
type. However, it is legal to overwrite elements of the map. The return
value is the template, so calls can be chained.
func (*Template) Lookup
func (t *Template) Lookup(name string) *Template
Lookup returns the template with the given name that is associated with t,
or nil if there is no such template.
func (*Template) Name
func (t *Template) Name() string
Name returns the name of the template.
func (*Template) New
func (t *Template) New(name string) *Template
New allocates a new template associated with the given one and with the same
delimiters. The association, which is transitive, allows one template to
invoke another with a {{template}} action.
func (*Template) Parse
func (t *Template) Parse(text string) (*Template, error)
Parse parses a string into a template. Nested template definitions will be
associated with the top-level template t. Parse may be called multiple times
to parse definitions of templates to associate with t. It is an error if a
resulting template is non-empty (contains content other than template
definitions) and would replace a non-empty template with the same name.
(In multiple calls to Parse with the same receiver template, only one call
can contain text other than space, comments, and template definitions.)
func (t *Template) ParseFiles(filenames ...string) (*Template, error)
ParseFiles parses the named files and associates the resulting templates with
t. If an error occurs, parsing stops and the returned template is nil;
otherwise it is t. There must be at least one file.
func (t *Template) ParseGlob(pattern string) (*Template, error)
ParseGlob parses the template definitions in the files identified by the
pattern and associates the resulting templates with t. The pattern is
processed by filepath.Glob and must match at least one file. ParseGlob is
equivalent to calling t.ParseFiles with the list of files matched by the
pattern.
func (t *Template) Templates() []*Template
Templates returns a slice of the templates associated with t, including t
itself.
Subdirectories
| Name |
|
Synopsis |
| .. |
| parse |
|
Package parse builds parse trees for templates as defined by text/template and html/template. |