亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄 搜索
archive archive/tar archive/zip bufio bufio(緩存) builtin builtin(內(nèi)置包) bytes bytes(包字節(jié)) compress compress/bzip2(壓縮/bzip2) compress/flate(壓縮/flate) compress/gzip(壓縮/gzip) compress/lzw(壓縮/lzw) compress/zlib(壓縮/zlib) container container/heap(容器數(shù)據(jù)結(jié)構(gòu)heap) container/list(容器數(shù)據(jù)結(jié)構(gòu)list) container/ring(容器數(shù)據(jù)結(jié)構(gòu)ring) context context(上下文) crypto crypto(加密) crypto/aes(加密/aes) crypto/cipher(加密/cipher) crypto/des(加密/des) crypto/dsa(加密/dsa) crypto/ecdsa(加密/ecdsa) crypto/elliptic(加密/elliptic) crypto/hmac(加密/hmac) crypto/md5(加密/md5) crypto/rand(加密/rand) crypto/rc4(加密/rc4) crypto/rsa(加密/rsa) crypto/sha1(加密/sha1) crypto/sha256(加密/sha256) crypto/sha512(加密/sha512) crypto/subtle(加密/subtle) crypto/tls(加密/tls) crypto/x509(加密/x509) crypto/x509/pkix(加密/x509/pkix) database database/sql(數(shù)據(jù)庫(kù)/sql) database/sql/driver(數(shù)據(jù)庫(kù)/sql/driver) debug debug/dwarf(調(diào)試/dwarf) debug/elf(調(diào)試/elf) debug/gosym(調(diào)試/gosym) debug/macho(調(diào)試/macho) debug/pe(調(diào)試/pe) debug/plan9obj(調(diào)試/plan9obj) encoding encoding(編碼) encoding/ascii85(編碼/ascii85) encoding/asn1(編碼/asn1) encoding/base32(編碼/base32) encoding/base64(編碼/base64) encoding/binary(編碼/binary) encoding/csv(編碼/csv) encoding/gob(編碼/gob) encoding/hex(編碼/hex) encoding/json(編碼/json) encoding/pem(編碼/pem) encoding/xml(編碼/xml) errors errors(錯(cuò)誤) expvar expvar flag flag(命令行參數(shù)解析flag包) fmt fmt go go/ast(抽象語法樹) go/build go/constant(常量) go/doc(文檔) go/format(格式) go/importer go/parser go/printer go/scanner(掃描儀) go/token(令牌) go/types(類型) hash hash(散列) hash/adler32 hash/crc32 hash/crc64 hash/fnv html html html/template(模板) image image(圖像) image/color(顏色) image/color/palette(調(diào)色板) image/draw(繪圖) image/gif image/jpeg image/png index index/suffixarray io io io/ioutil log log log/syslog(日志系統(tǒng)) math math math/big math/big math/bits math/bits math/cmplx math/cmplx math/rand math/rand mime mime mime/multipart(多部分) mime/quotedprintable net net net/http net/http net/http/cgi net/http/cookiejar net/http/fcgi net/http/httptest net/http/httptrace net/http/httputil net/http/internal net/http/pprof net/mail net/mail net/rpc net/rpc net/rpc/jsonrpc net/smtp net/smtp net/textproto net/textproto net/url net/url os os os/exec os/signal os/user path path path/filepath(文件路徑) plugin plugin(插件) reflect reflect(反射) regexp regexp(正則表達(dá)式) regexp/syntax runtime runtime(運(yùn)行時(shí)) runtime/debug(調(diào)試) runtime/internal/sys runtime/pprof runtime/race(競(jìng)爭(zhēng)) runtime/trace(執(zhí)行追蹤器) sort sort(排序算法) strconv strconv(轉(zhuǎn)換) strings strings(字符串) sync sync(同步) sync/atomic(原子操作) syscall syscall(系統(tǒng)調(diào)用) testing testing(測(cè)試) testing/iotest testing/quick text text/scanner(掃描文本) text/tabwriter text/template(定義模板) text/template/parse time time(時(shí)間戳) unicode unicode unicode/utf16 unicode/utf8 unsafe unsafe
文字

  • import "text/template"

  • 概觀

  • 索引

  • Examples

  • 子目錄

概觀

打包模板實(shí)現(xiàn)了用于生成文本輸出的數(shù)據(jù)驅(qū)動(dòng)模板。

要生成 HTML 輸出,請(qǐng)參閱包 html / template ,它與此包具有相同的接口,但會(huì)自動(dòng)保護(hù) HTML 輸出免受某些攻擊。

通過將模板應(yīng)用于數(shù)據(jù)結(jié)構(gòu)來執(zhí)行模板。模板中的注釋引用數(shù)據(jù)結(jié)構(gòu)的元素(通常是結(jié)構(gòu)中的字段或映射中的鍵)來控制執(zhí)行并導(dǎo)出要顯示的值。模板的執(zhí)行遍歷結(jié)構(gòu)并設(shè)置光標(biāo),以句點(diǎn)'。'表示。并稱為“點(diǎn)”,作為執(zhí)行過程中結(jié)構(gòu)中當(dāng)前位置的值。

模板的輸入文本是任何格式的 UTF-8 編碼文本?!靶袆?dòng)” - 數(shù)據(jù)評(píng)估或控制結(jié)構(gòu) - 由“{{”和“}}”分隔。所有文本以外的動(dòng)作都將被復(fù)制到輸出中。除了原始字符串,操作可能不會(huì)跨越換行符,盡管注釋可以。

一旦解析,模板可以并行安全地執(zhí)行,但如果并行執(zhí)行共享 Writer,則輸出可能會(huì)交錯(cuò)。

這是一個(gè)簡(jiǎn)單的例子,打印出“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) }

下面顯示更復(fù)雜的例子。

文本和空格

默認(rèn)情況下,在執(zhí)行模板時(shí),動(dòng)作之間的所有文本都會(huì)逐字復(fù)制。例如,在程序運(yùn)行時(shí),上述示例中的字符串“由...構(gòu)成”出現(xiàn)在標(biāo)準(zhǔn)輸出中。

但是,為了幫助格式化模板源代碼,如果動(dòng)作的左分隔符(默認(rèn)為“{{”)后面緊跟著一個(gè)減號(hào)和 ASCII 空格字符(“{{ - ”)),則所有尾隨空白符將從緊接在文本之前。同樣,如果右分隔符(“}}”)前面有空格和減號(hào)(“ - }}”),則所有前導(dǎo)空格都將從緊隨其后的文本中刪除。在這些修剪標(biāo)記中,ASCII空間必須存在; “{{-3}}”解析為包含數(shù)字-3的操作。

例如,當(dāng)執(zhí)行源代碼為的模板時(shí)

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

生成的輸出將是

"23<45"

對(duì)于這種修剪,空白字符的定義與 Go :空格,水平制表符,回車符和換行符相同。

操作

這是行動(dòng)列表。“參數(shù)”和“管道”是對(duì)數(shù)據(jù)的評(píng)估,在后面的相應(yīng)部分詳細(xì)說明。

{{/* a comment */}}
	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 actionof 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 elementsof 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" .}}
	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.

參數(shù)

參數(shù)是一個(gè)簡(jiǎn)單的值,表示為以下之一。

- A boolean, string, character, integer, floating-point, imaginary
  or complex constant in Go syntax. These behave like Go's untyped
  constants.- 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

參數(shù)可以評(píng)估為任何類型;如果它們是指針,則實(shí)現(xiàn)會(huì)在需要時(shí)自動(dòng)指向基本類型。如果一個(gè)評(píng)估產(chǎn)生一個(gè)函數(shù)值,比如一個(gè) struct 的函數(shù)值域,那么該函數(shù)不會(huì)被自動(dòng)調(diào)用,但它可以用作 if 動(dòng)作等的真值。要調(diào)用它,請(qǐng)使用下面定義的調(diào)用函數(shù)。

管道

流水線是可能鏈接的“命令”序列。命令是一個(gè)簡(jiǎn)單的值(參數(shù))或函數(shù)或方法調(diào)用,可能有多個(gè)參數(shù):

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 associatedwith the name:function(Argument1, etc.)
	Functions and function names are described below.

管道可以通過用流水線字符 '|' 分隔一系列命令來“鏈接”。在鏈?zhǔn)焦艿乐校總€(gè)命令的結(jié)果都作為以下命令的最后一個(gè)參數(shù)傳遞。管道中最終命令的輸出是管道的值。

命令的輸出可以是一個(gè)值或兩個(gè)值,其中第二個(gè)具有類型錯(cuò)誤。如果第二個(gè)值存在并且評(píng)估為非零,則執(zhí)行終止,并將錯(cuò)誤返回給執(zhí)行的調(diào)用者。

變量

動(dòng)作中的管道可以初始化一個(gè)變量來捕獲結(jié)果。初始化有語法

$variable := pipeline

其中 $ variable 是變量的名稱。聲明變量的動(dòng)作不會(huì)產(chǎn)生輸出。

如果“范圍”操作初始化一個(gè)變量,則該變量將設(shè)置為迭代的連續(xù)元素。此外,“范圍”可以聲明兩個(gè)變量,用逗號(hào)分隔:

range $index, $element := pipeline

在這種情況下,$ index 和 $ element 分別被設(shè)置為數(shù)組/索引或映射鍵和元素的連續(xù)值。請(qǐng)注意,如果只有一個(gè)變量,則會(huì)分配該元素; 這與 Go 范圍內(nèi)的約定相反。

變量的作用域擴(kuò)展到聲明它的控制結(jié)構(gòu)(“if”,“with”或“range”)的“end”動(dòng)作,或者如果沒有這樣的控制結(jié)構(gòu),則擴(kuò)展到模板的末尾。模板調(diào)用不會(huì)從其調(diào)用點(diǎn)繼承變量。

當(dāng)執(zhí)行開始時(shí),$ 被設(shè)置為傳遞給 Execute 的數(shù)據(jù)參數(shù),也就是點(diǎn)的起始值。

示例

下面是一些演示流水線和變量的單行模板示例。所有產(chǎn)生引用的單詞“輸出”:

{{"\"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.

功能

在執(zhí)行期間,函數(shù)可以在兩個(gè)函數(shù)圖中找到:首先在模板中,然后在全局函數(shù)圖中找到。默認(rèn)情況下,模板中沒有定義函數(shù),但可以使用 Funcs 方法添加它們。

預(yù)定義的全局函數(shù)名稱如下。

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 mustreturn 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 unavailablein 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.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.

布爾函數(shù)將任何零值設(shè)為 false,并將非零值設(shè)為 true。

還有一組定義為函數(shù)的二進(jìn)制比較運(yùn)算符:

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

對(duì)于更簡(jiǎn)單的多路平等測(cè)試,eq(only)接受兩個(gè)或更多個(gè)參數(shù),并比較第一個(gè)和后面的第一個(gè),返回有效

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

(與 Go 中的||不同,然而,eq 是一個(gè)函數(shù)調(diào)用,所有參數(shù)都將被評(píng)估。)

比較函數(shù)僅適用于基本類型(或指定的基本類型,例如“類型 Celsius float32”)。它們實(shí)現(xiàn) Go 規(guī)則以比較值,但忽略大小和確切類型,因此可以將任何有符號(hào)或無符號(hào)整數(shù)值與任何其他整數(shù)值進(jìn)行比較。(算術(shù)值被比較,而不是比特模式,因此所有負(fù)整數(shù)都小于所有無符號(hào)整數(shù)。)但是,像往常一樣,不能將 int 與 float32 等進(jìn)行比較。

關(guān)聯(lián)的模板

每個(gè)模板都由創(chuàng)建時(shí)指定的字符串命名。而且,每個(gè)模板都與零個(gè)或多個(gè)其他模板相關(guān)聯(lián),可以按名稱調(diào)用它們;這種關(guān)聯(lián)是可傳遞的,并形成模板的名稱空間。

模板可以使用模板調(diào)用來實(shí)例化另一個(gè)相關(guān)聯(lián)的模板;請(qǐng)參閱上面“模板”操作的解釋。該名稱必須是與包含該調(diào)用的模板關(guān)聯(lián)的模板的名稱。

嵌套的模板定義

解析模板時(shí),可能會(huì)定義另一個(gè)模板并將其與正在解析的模板關(guān)聯(lián)。模板定義必須出現(xiàn)在模板的頂層,非常像 Go 程序中的全局變量。

這些定義的語法是用“定義”和“結(jié)束”動(dòng)作包圍每個(gè)模板聲明。

定義操作通過提供字符串常量來命名正在創(chuàng)建的模板。這是一個(gè)簡(jiǎn)單的例子:

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

這定義了兩個(gè)模板 T1 和 T2,以及第三個(gè) T3 在執(zhí)行時(shí)調(diào)用其他兩個(gè)模板。最后它調(diào)用 T3。如果執(zhí)行此模板將生成文本

ONE TWO

通過構(gòu)建,模板可以僅存在于一個(gè)關(guān)聯(lián)中。如果必須有可從多個(gè)關(guān)聯(lián)中尋址的模板,則必須多次解析模板定義以創(chuàng)建不同的 * Template 值,或者必須使用 Clone 或 AddParseTree 方法復(fù)制該模板定義。

可以多次調(diào)用解析來組裝各種關(guān)聯(lián)的模板;請(qǐng)參閱 ParseFiles 和 ParseGlob 函數(shù)和方法,以獲取解析存儲(chǔ)在文件中的相關(guān)模板的簡(jiǎn)單方法。

模板可以直接執(zhí)行或通過 ExecuteTemplate 執(zhí)行,后者執(zhí)行由名稱標(biāo)識(shí)的相關(guān)模板。為了調(diào)用我們上面的例子,我們可以寫,

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

或通過名稱顯式調(diào)用特定的模板,

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

索引

  • 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

  • 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

示例

Template Template (Block) Template (Func) Template (Glob) Template (Helpers) Template (Share)

打包文件

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

func HTMLEscape

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

HTMLEscape 寫入到明文數(shù)據(jù) b 的轉(zhuǎn)義 HTML 等價(jià)物中。

func HTMLEscapeString

func HTMLEscapeString(s string) string

HTMLEscapeString 返回純文本數(shù)據(jù)的轉(zhuǎn)義 HTML 等價(jià)物。

func HTMLEscaper

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

HTMLEscaper 返回其參數(shù)文本表示的轉(zhuǎn)義 HTML 等價(jià)物。

func IsTrue

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

IsTrue 報(bào)告該值是否為'真',意味著它的類型不為零,以及該值是否具有有意義的真值。這是if和其他此類行為所使用的真相的定義。

func JSEscape

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

JSEscape 寫入 w 的純文本數(shù)據(jù) b 的逃逸 JavaScript 等價(jià)物。

func JSEscapeString

func JSEscapeString(s string) string

JSEscapeString 返回純文本數(shù)據(jù)的轉(zhuǎn)義 JavaScript 等價(jià)物。

func JSEscaper

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

JSEscaper 返回其參數(shù)的文本表示的轉(zhuǎn)義 JavaScript 等價(jià)物。

func URLQueryEscaper

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

URLQueryEscaper 以適合于嵌入到 URL 查詢中的形式返回其參數(shù)的文本表示的轉(zhuǎn)義值。

type ExecError

ExecError 是 Execute 在評(píng)估其模板時(shí)發(fā)生錯(cuò)誤時(shí)返回的自定義錯(cuò)誤類型。(如果發(fā)生寫入錯(cuò)誤,則返回實(shí)際錯(cuò)誤;它不會(huì)是 ExecError 類型。)

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

func (ExecError) Error

func (e ExecError) Error() string

鍵入FuncMap

FuncMap 是定義從名稱到函數(shù)映射的映射的類型。每個(gè)函數(shù)必須具有單個(gè)返回值,或者其中第二個(gè)具有類型錯(cuò)誤的返回值。在這種情況下,如果第二個(gè)(錯(cuò)誤)返回值在執(zhí)行過程中評(píng)估為非零,則執(zhí)行結(jié)束,并執(zhí)行返回該錯(cuò)誤。

當(dāng)模板執(zhí)行使用參數(shù)列表調(diào)用函數(shù)時(shí),該列表必須可分配給函數(shù)的參數(shù)類型。旨在應(yīng)用于任意類型參數(shù)的函數(shù)可以使用類型為 interface {} 或類型為 reflect.Value 的參數(shù)。同樣,函數(shù)意味著返回任意類型的結(jié)果,可以返回 interface {} 或 reflect.Value。

type FuncMap map[string]interface{}

鍵入Template

Template 是分析模板的表示。* parse.Tree字段僅導(dǎo)出供 html / template 使用,并應(yīng)被視為未被所有其他客戶端導(dǎo)出。

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

示例

package mainimport ("log""os""text/template")func main() {// Define a template.const letter = `
Dear {{.Name}},
{{if .Attended}}
It was a pleasure to see you at the wedding.
{{- else}}
It is a shame you couldn't make it to the wedding.
{{- end}}
{{with .Gift -}}
Thank you for the lovely {{.}}.
{{end}}
Best wishes,
Josie
`// Prepare some data to insert into the template.
	type Recipient struct {
		Name, Gift string
		Attended   bool}var recipients = []Recipient{{"Aunt Mildred", "bone china tea set", true},{"Uncle John", "moleskin pants", false},{"Cousin Rodney", "", false},}// Create a new template and parse the letter into it.
	t := template.Must(template.New("letter").Parse(letter))// Execute the template for each recipient.for _, r := range recipients {
		err := t.Execute(os.Stdout, r)if err != nil {
			log.Println("executing template:", err)}}}

示例(塊)

package mainimport ("log""os""strings""text/template")func main() {const (
		master  = `Names:{{block "list" .}}{{"\n"}}{{range .}}{{println "-" .}}{{end}}{{end}}`
		overlay = `{{define "list"}} {{join . ", "}}{{end}} `)var (
		funcs     = template.FuncMap{"join": strings.Join}
		guardians = []string{"Gamora", "Groot", "Nebula", "Rocket", "Star-Lord"})
	masterTmpl, err := template.New("master").Funcs(funcs).Parse(master)if err != nil {
		log.Fatal(err)}
	overlayTmpl, err := template.Must(masterTmpl.Clone()).Parse(overlay)if err != nil {
		log.Fatal(err)}if err := masterTmpl.Execute(os.Stdout, guardians); err != nil {
		log.Fatal(err)}if err := overlayTmpl.Execute(os.Stdout, guardians); err != nil {
		log.Fatal(err)}}

示例(Func)

此示例演示了處理模板文本的自定義函數(shù)。它會(huì)安裝 strings.Title 函數(shù)并使用它在我們的模板輸出中使標(biāo)題文字看起來很好。

package mainimport ("log""os""strings""text/template")func main() {// First we create a FuncMap with which to register the function.
	funcMap := template.FuncMap{// The name "title" is what the function will be called in the template text."title": strings.Title,}// A simple template definition to test our function.// We print the input text several ways:// - the original// - title-cased// - title-cased and then printed with %q// - printed with %q and then title-cased.const templateText = `
Input: {{printf "%q" .}}
Output 0: {{title .}}
Output 1: {{title . | printf "%q"}}
Output 2: {{printf "%q" . | title}}
`// Create a template, add the function map, and parse the text.
	tmpl, err := template.New("titleTest").Funcs(funcMap).Parse(templateText)if err != nil {
		log.Fatalf("parsing: %s", err)}// Run the template to verify the output.
	err = tmpl.Execute(os.Stdout, "the go programming language")if err != nil {
		log.Fatalf("execution: %s", err)}}

示例(Glob)

這里我們演示從目錄加載一組模板。

編碼:

// Here we create a temporary directory and populate it with our sample// template definition files; usually the template files would already// exist in some location known to the program.dir := createTestDir([]templateFile{        // T0.tmpl is a plain template file that just invokes T1.        {"T0.tmpl", `T0 invokes T1: ({{template "T1"}})`},        // T1.tmpl defines a template, T1 that invokes T2.        {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},        // T2.tmpl defines a template T2.        {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},})// Clean up after the test; another quirk of running as an example.defer os.RemoveAll(dir)// pattern is the glob pattern used to find all the template files.pattern := filepath.Join(dir, "*.tmpl")// Here starts the example proper.// T0.tmpl is the first name matched, so it becomes the starting template,// the value returned by ParseGlob.tmpl := template.Must(template.ParseGlob(pattern))err := tmpl.Execute(os.Stdout, nil)if err != nil {
        log.Fatalf("template execution: %s", err)}

輸出:

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

示例(Helpers)

此示例演示了共享某些模板并在不同環(huán)境中使用它們的一種方法。在這個(gè)變體中,我們手動(dòng)添加多個(gè)驅(qū)動(dòng)模板到現(xiàn)有的一組模板。

編碼:

// Here we create a temporary directory and populate it with our sample// template definition files; usually the template files would already// exist in some location known to the program.dir := createTestDir([]templateFile{        // T1.tmpl defines a template, T1 that invokes T2.        {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},        // T2.tmpl defines a template T2.        {"T2.tmpl", `{{define "T2"}}This is T2{{end}}`},})// Clean up after the test; another quirk of running as an example.defer os.RemoveAll(dir)// pattern is the glob pattern used to find all the template files.pattern := filepath.Join(dir, "*.tmpl")// Here starts the example proper.// Load the helpers.templates := template.Must(template.ParseGlob(pattern))// Add one driver template to the bunch; we do this with an explicit template definition._, err := templates.Parse("{{define `driver1`}}Driver 1 calls T1: ({{template `T1`}})\n{{end}}")if err != nil {
        log.Fatal("parsing driver1: ", err)}// Add another driver template._, err = templates.Parse("{{define `driver2`}}Driver 2 calls T2: ({{template `T2`}})\n{{end}}")if err != nil {
        log.Fatal("parsing driver2: ", err)}// We load all the templates before execution. This package does not require// that behavior but html/template's escaping does, so it's a good habit.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)}

輸出:

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

示例(Share)

本示例演示如何將一組驅(qū)動(dòng)程序模板與不同的輔助程序模板集一起使用。

編碼:

// Here we create a temporary directory and populate it with our sample// template definition files; usually the template files would already// exist in some location known to the program.dir := createTestDir([]templateFile{        // T0.tmpl is a plain template file that just invokes T1.        {"T0.tmpl", "T0 ({{.}} version) invokes T1: ({{template `T1`}})\n"},        // T1.tmpl defines a template, T1 that invokes T2. Note T2 is not defined        {"T1.tmpl", `{{define "T1"}}T1 invokes T2: ({{template "T2"}}){{end}}`},})// Clean up after the test; another quirk of running as an example.defer os.RemoveAll(dir)// pattern is the glob pattern used to find all the template files.pattern := filepath.Join(dir, "*.tmpl")// Here starts the example proper.// Load the drivers.drivers := template.Must(template.ParseGlob(pattern))// We must define an implementation of the T2 template. First we clone// the drivers, then add a definition of T2 to the template name space.// 1. Clone the helper set to create a new name space from which to run them.first, err := drivers.Clone()if err != nil {
        log.Fatal("cloning helpers: ", err)}// 2. Define T2, version A, and parse it._, err = first.Parse("{{define `T2`}}T2, version A{{end}}")if err != nil {
        log.Fatal("parsing T2: ", err)}// Now repeat the whole thing, using a different version of T2.// 1. Clone the drivers.second, err := drivers.Clone()if err != nil {
        log.Fatal("cloning drivers: ", err)}// 2. Define T2, version B, and parse it._, err = second.Parse("{{define `T2`}}T2, version B{{end}}")if err != nil {
        log.Fatal("parsing T2: ", err)}// Execute the templates in the reverse order to verify the// first is unaffected by the second.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)}

輸出:

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 必須是一個(gè)幫助函數(shù),如果錯(cuò)誤不為零,它會(huì)將函數(shù)調(diào)用返回(* Template,error)并發(fā)生混亂。它旨在用于變量初始化,如

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

func New

func New(name string) *Template

New 使用給定的名稱分配一個(gè)新的,未定義的模板。

func ParseFiles

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

ParseFiles 創(chuàng)建一個(gè)新的模板并從命名文件中解析模板定義。返回的模板名稱將具有第一個(gè)文件的基本名稱和解析內(nèi)容。必須至少有一個(gè)文件。如果發(fā)生錯(cuò)誤,解析將停止,返回的 * Template 將為零。

當(dāng)在不同的目錄中分析具有相同名稱的多個(gè)文件時(shí),提到的最后一個(gè)將是結(jié)果。例如, ParseFiles(“a / foo”,“b / foo”)存儲(chǔ)“b / foo”作為名為“foo”的模板,而“a / foo”不可用。

func ParseGlob

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

ParseGlob 創(chuàng)建一個(gè)新的模板并分析模式標(biāo)識(shí)的文件中的模板定義,該文件必須至少匹配一個(gè)文件。返回的模板將具有與該模式匹配的第一個(gè)文件的(基本)名稱和(已分析)內(nèi)容。 ParseGlob 相當(dāng)于使用模式匹配的文件列表調(diào)用 ParseFiles 。

當(dāng)在不同的目錄中分析具有相同名稱的多個(gè)文件時(shí),提到的最后一個(gè)將是結(jié)果。

func (*Template) AddParseTree

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

AddParseTree 為具有給定名稱的模板添加解析樹并將其與t關(guān)聯(lián)。如果該模板不存在,它將創(chuàng)建一個(gè)新模板。如果模板確實(shí)存在,它將被替換。

func (*Template) Clone

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

Clone 返回模板的副本,包括所有關(guān)聯(lián)的模板。實(shí)際表示不會(huì)被復(fù)制,但是相關(guān)模板的名稱空間是,因此對(duì)副本中的分析進(jìn)一步調(diào)用會(huì)將模板添加到副本,但不會(huì)添加到原始模板??梢允褂每寺碇苽渫ㄓ媚0?,并在制作克隆后通過添加變體來將它們與其他模板的變體定義一起使用。

func (*Template) DefinedTemplates

func (t *Template) DefinedTemplates() string

DefinedTemplates 返回一個(gè)字符串,列出定義的模板,以字符串“;定義的模板為:”為前綴。如果沒有,則返回空字符串。用于在這里和 HTML /模板中生成錯(cuò)誤消息。

func (*Template) Delims

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

Delims 將動(dòng)作分隔符設(shè)置為指定的字符串,以便在隨后調(diào)用 Parse,ParseFiles或ParseGlob 時(shí)使用。嵌套模板定義將繼承這些設(shè)置。一個(gè)空的分隔符表示相應(yīng)的默認(rèn)值:{{或}}。返回值是模板,因此可以將調(diào)用鏈接起來。

func (*Template) Execute

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

執(zhí)行將解析的模板應(yīng)用于指定的數(shù)據(jù)對(duì)象,并將輸出寫入到 wr。如果執(zhí)行模板或?qū)懭肫漭敵鰰r(shí)發(fā)生錯(cuò)誤,則執(zhí)行停止,但部分結(jié)果可能已寫入輸出寫入器。模板可以并行安全地執(zhí)行,但如果并行執(zhí)行共享 Writer ,輸出可能會(huì)交錯(cuò)。

如果數(shù)據(jù)是 reflect.Value,則該模板將應(yīng)用于 reflect.Value 保留的具體值,如 fmt.Print 中所示。

func (*Template) ExecuteTemplate

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

ExecuteTemplate 將與具有給定名稱的t關(guān)聯(lián)的模板應(yīng)用于指定的數(shù)據(jù)對(duì)象,并將輸出寫入 wr。如果執(zhí)行模板或?qū)懭肫漭敵鰰r(shí)發(fā)生錯(cuò)誤,則執(zhí)行停止,但部分結(jié)果可能已寫入輸出寫入器。模板可以并行安全地執(zhí)行,但如果并行執(zhí)行共享 Writer,輸出可能會(huì)交錯(cuò)。

func (*Template) Funcs

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

Funcs 將參數(shù)圖的元素添加到模板的功能圖中。它必須在解析模板之前調(diào)用。如果映射中的值不是具有適當(dāng)返回類型的函數(shù),或者該名稱不能在語法上作為模板中的函數(shù)使用,那么它會(huì)發(fā)生混亂。覆蓋地圖的元素是合法的。返回值是模板,因此可以將調(diào)用鏈接起來。

func (*Template) Lookup

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

查找將返回與 t 關(guān)聯(lián)的給定名稱的模板。如果沒有這樣的模板或模板沒有定義,它將返回 nil。

func (*Template) Name

func (t *Template) Name() string

Name 返回模板的名稱。

func (*Template) New

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

New 分配一個(gè)新的,未定義的模板與給定的和相同的分隔符相關(guān)聯(lián)。該關(guān)聯(lián)是可傳遞的,它允許一個(gè)模板通過 {{template}} 動(dòng)作調(diào)用另一個(gè)模板。

func (*Template) Option

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

選項(xiàng)為模板設(shè)置選項(xiàng)。選項(xiàng)由字符串描述,可以是簡(jiǎn)單字符串或“key = value”。選項(xiàng)字符串中最多只能有一個(gè)等號(hào)。如果選項(xiàng)字符串無法識(shí)別或無效,則選項(xiàng)會(huì)出現(xiàn)混亂。

已知選項(xiàng):

missingkey:如果地圖使用地圖中不存在的鍵索引,則控制執(zhí)行過程中的行為。

"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 關(guān)聯(lián)的附加模板,并從 t 本身的定義中刪除。

連續(xù)調(diào)用 Parse 可以重新定義模板。包含僅包含空格和注釋的主體的模板定義被視為空白,并且不會(huì)替換現(xiàn)有模板的主體。這允許使用Parse添加新的命名模板定義而不覆蓋主模板主體。

func (*Template) ParseFiles

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

ParseFiles 解析命名文件并將生成的模板與 t 關(guān)聯(lián)。如果發(fā)生錯(cuò)誤,解析將停止并且返回的模板為零;否則是 t。必須至少有一個(gè)文件。由于由 ParseFiles 創(chuàng)建的模板是由參數(shù)文件的基名命名的,所以 t 通常應(yīng)該具有文件的(基)名之一的名稱。如果沒有,則根據(jù)調(diào)用  ParseFiles 之前的內(nèi)容,t.Execute 可能會(huì)失敗。在這種情況下,使用 t.ExecuteTemplate 執(zhí)行一個(gè)有效的模板。

當(dāng)在不同的目錄中分析具有相同名稱的多個(gè)文件時(shí),提到的最后一個(gè)將是結(jié)果。

func (*Template) ParseGlob

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

ParseGlob 解析由模式標(biāo)識(shí)的文件中的模板定義,并將生成的模板與 t 關(guān)聯(lián)。該模式由 filepath.Glob 處理,并且必須至少匹配一個(gè)文件。ParseGlob 相當(dāng)于使用模式匹配的文件列表調(diào)用 t.ParseFiles。

當(dāng)在不同的目錄中分析具有相同名稱的多個(gè)文件時(shí),提到的最后一個(gè)將是結(jié)果。

func (*Template) Templates

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

模板返回一個(gè)與 t 關(guān)聯(lián)的定義模板。

子目錄

名稱

概要

| .. |

|  parse | 打包 parse 構(gòu)建為 text / template 和 html / template 定義的模板分析樹。|

上一篇: 下一篇: