URL
https://opencores.org/ocsvn/openrisc/openrisc/trunk
Subversion Repositories openrisc
[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libgo/] [go/] [text/] [template/] [doc.go] - Rev 747
Compare with Previous | Blame | View Log
// Copyright 2011 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file./*Package template implements data-driven templates for generating textual outputsuch as HTML.Templates are executed by applying them to a data structure. Annotations in thetemplate refer to elements of the data structure (typically a field of a structor a key in a map) to control execution and derive values to be displayed.Execution of the template walks the structure and sets the cursor, representedby a period '.' and called "dot", to the value at the current location in thestructure as execution proceeds.The input text for a template is UTF-8-encoded text in any format."Actions"--data evaluations or control structures--are delimited by"{{" and "}}"; all text outside actions is copied to the output unchanged.Actions may not span newlines, although comments can.Once constructed, a template may be executed safely in parallel.ActionsHere is the list of actions. "Arguments" and "pipelines" are evaluations ofdata, defined in detail below.*/// {{/* a comment */}}// A comment; discarded. May contain newlines.// Comments do not nest./*{{pipeline}}The default textual representation of the value of the pipelineis 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, anynil pointer or interface value, and any array, slice, map, orstring 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.{{range pipeline}} T1 {{end}}The value of the pipeline must be an array, slice, or map. Ifthe 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 thekeys are of basic type with a defined order ("comparable"), theelements will be visited in sorted key order.{{range pipeline}} T1 {{else}} T0 {{end}}The value of the pipeline must be an array, slice, or map. Ifthe value of the pipeline has length zero, dot is unaffected andT0 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 setto the value of the pipeline.{{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 isexecuted.{{with pipeline}} T1 {{else}} T0 {{end}}If the value of the pipeline is empty, dot is unaffected and T0is executed; otherwise, dot is set to the value of the pipelineand T1 is executed.ArgumentsAn argument is a simple value, denoted by one of the following.- A boolean, string, character, integer, floating-point, imaginaryor complex constant in Go syntax. These behave like Go's untypedconstants, although raw strings may not span newlines.- The character '.' (period):.The result is the value of dot.- A variable name, which is a (possibly empty) alphanumeric stringpreceded by a dollar sign, such as$piOver2or$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, precededby a period, such as.FieldThe result is the value of the field. Field invocations may bechained:.Field1.Field2Fields can also be evaluated on variables, including chaining:$x.Field1.Field2- The name of a key of the data, which must be a map, precededby a period, such as.KeyThe result is the map element value indexed by the key.Key invocations may be chained and combined with fields to anydepth:.Field1.Key1.Field2.Key2Although the key must be an alphanumeric identifier, unlike withfield 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.MethodThe result is the value of invoking the method with dot as thereceiver, dot.Method(). Such a method must have one return value (ofany type) or two return values, the second of which is an error.If it has two and the returned error is non-nil, execution terminatesand an error is returned to the caller as the value of Execute.Method invocations may be chained and combined with fields and keysto any depth:.Field1.Key1.Method1.Field2.Key2.Method2Methods can also be evaluated on variables, including chaining:$x.Method1.Field- The name of a niladic function, such asfunThe result is the value of invoking the function, fun(). The returntypes and values behave as in methods. Functions and functionnames are described below.Arguments may evaluate to any type; if they are pointers the implementationautomatically indirects to the base type when required.A pipeline is a possibly chained sequence of "commands". A command is a simplevalue (argument) or a function or method call, possibly with multiple arguments:ArgumentThe 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 thearguments: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.PipelinesA pipeline may be "chained" by separating a sequence of commands with pipelinecharacters '|'. In a chained pipeline, the result of the each command ispassed as the last argument of the following command. The output of the finalcommand in the pipeline is the value of the pipeline.The output of a command will be either one value or two values, the second ofwhich has type error. If that second value is present and evaluates tonon-nil, execution terminates and the error is returned to the caller ofExecute.VariablesA pipeline inside an action may initialize a variable to capture the result.The initialization has syntax$variable := pipelinewhere $variable is the name of the variable. An action that declares avariable produces no output.If a "range" action initializes a variable, the variable is set to thesuccessive elements of the iteration. Also, a "range" may declare twovariables, separated by a comma:$index, $element := pipelinein which case $index and $element are set to the successive values of thearray/slice index or map key and element, respectively. Note that if there isonly one variable, it is assigned the element; this is opposite to theconvention in Go range clauses.A variable's scope extends to the "end" action of the control structure ("if","with", or "range") in which it is declared, or to the end of the template ifthere is no such control structure. A template invocation does not inheritvariables from the point of its invocation.When execution begins, $ is set to the data argument passed to Execute, that is,to the starting value of dot.ExamplesHere are some example one-line templates demonstrating pipelines and variables.All produce the quoted word "output":{{"\"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 previouscommand.{{"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.FunctionsDuring execution functions are found in two function maps: first in thetemplate, then in the global function map. By default, no functions are definedin the template but the Funcs methods can be used to add them.Predefined global functions are named as follows.andReturns the boolean AND of its arguments by returning thefirst empty argument or the last argument, that is,"and x y" behaves as "if x then y else x". All thearguments are evaluated.htmlReturns the escaped HTML equivalent of the textualrepresentation of its arguments.indexReturns the result of indexing its first argument by thefollowing 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.jsReturns the escaped JavaScript equivalent of the textualrepresentation of its arguments.lenReturns the integer length of its argument.notReturns the boolean negation of its single argument.orReturns the boolean OR of its arguments by returning thefirst non-empty argument or the last argument, that is,"or x y" behaves as "if x then x else y". All thearguments are evaluated.An alias for fmt.SprintprintfAn alias for fmt.SprintfprintlnAn alias for fmt.SprintlnurlqueryReturns the escaped value of the textual representation ofits arguments in a form suitable for embedding in a URL query.The boolean functions take any zero value to be false and a non-zero value tobe true.Associated templatesEach template is named by a string specified when it is created. Also, eachtemplate is associated with zero or more other templates that it may invoke byname; such associations are transitive and form a name space of templates.A template may use a template invocation to instantiate another associatedtemplate; see the explanation of the "template" action above. The name must bethat of a template associated with the template that contains the invocation.Nested template definitionsWhen parsing a template, another template may be defined and associated with thetemplate being parsed. Template definitions must appear at the top level of thetemplate, much like global variables in a Go program.The syntax of such definitions is to surround each template declaration with a"define" and "end" action.The define action names the template being created by providing a stringconstant. Here is a simple example:`{{define "T1"}}ONE{{end}}{{define "T2"}}TWO{{end}}{{define "T3"}}{{template "T1"}} {{template "T2"}}{{end}}{{template "T3"}}`This defines two templates, T1 and T2, and a third T3 that invokes the other twowhen it is executed. Finally it invokes T3. If executed this template willproduce the textONE TWOBy construction, a template may reside in only one association. If it'snecessary to have a template addressable from multiple associations, thetemplate definition must be parsed multiple times to create distinct *Templatevalues.Parse may be called multiple times to assemble the various associated templates;see the ParseFiles and ParseGlob functions and methods for simple ways to parserelated templates stored in files.A template may be executed directly or through ExecuteTemplate, which executesan associated template identified by name. To invoke our example above, wemight write,err := tmpl.Execute(os.Stdout, "no data needed")if err != nil {log.Fatalf("execution failed: %s", err)}or to invoke a particular template explicitly by name,err := tmpl.ExecuteTemplate(os.Stdout, "T2", "no data needed")if err != nil {log.Fatalf("execution failed: %s", err)}*/package template
