https://godoc.org/text/template

Go: text/templateIndex | Examples | Files | Directories

package template

import "text/template"

Package template implements data-driven templates for generating textual output.

To generate HTML output, see package html/template, which has the same interface as this package but automatically secures HTML output against certain attacks.

Templates are executed by applying them to a data structure. Annotations in the template refer to elements of the data structure (typically a field of a struct or 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, represented by a period '.' and called "dot", to the value at the current location in the structure 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. Except for raw strings, actions may not span newlines, although comments can.

Once parsed, a template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved.

Here is a trivial example that prints "17 items are made of wool".

  1. type Inventory struct {
  2. Material string
  3. Count uint
  4. }
  5. sweaters := Inventory{"wool", 17}
  6. tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")
  7. if err != nil { panic(err) }
  8. err = tmpl.Execute(os.Stdout, sweaters)
  9. if err != nil { panic(err) }

More intricate examples appear below.

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.

However, to aid in formatting template source code, if an action's left delimiter (by default "{{") is followed immediately by a minus sign and ASCII space character ("{{- "), all trailing white space is trimmed from the immediately preceding text. Similarly, if the right delimiter ("}}") is preceded by a space and minus sign (" -}}"), all leading white space is trimmed from the immediately following text. In these trim markers, the ASCII space must be present; "{{-3}}" parses as an action containing the number -3.

For instance, when executing the template whose source is

  1. "{{23 -}} < {{- 45}}"

the generated output would be

  1. "23<45"

For this trimming, the definition of white space characters is the same as in Go: space, horizontal tab, carriage return, and newline.

Actions

Here is the list of actions. "Arguments" and "pipelines" are evaluations of data, defined in detail in the corresponding sections that follow.

  1. {{/* a comment */}}
  2. {{- /* a comment with white space trimmed from preceding and following text */ -}}
  3. A comment; discarded. May contain newlines.
  4. Comments do not nest and must start and end at the
  5. delimiters, as shown here.
  6.  
  7. {{pipeline}}
  8. The default textual representation (the same as would be
  9. printed by fmt.Print) of the value of the pipeline is copied
  10. to the output.
  11.  
  12. {{if pipeline}} T1 {{end}}
  13. If the value of the pipeline is empty, no output is generated;
  14. otherwise, T1 is executed. The empty values are false, 0, any
  15. nil pointer or interface value, and any array, slice, map, or
  16. string of length zero.
  17. Dot is unaffected.
  18.  
  19. {{if pipeline}} T1 {{else}} T0 {{end}}
  20. If the value of the pipeline is empty, T0 is executed;
  21. otherwise, T1 is executed. Dot is unaffected.
  22.  
  23. {{if pipeline}} T1 {{else if pipeline}} T0 {{end}}
  24. To simplify the appearance of if-else chains, the else action
  25. of an if may include another if directly; the effect is exactly
  26. the same as writing
  27. {{if pipeline}} T1 {{else}}{{if pipeline}} T0 {{end}}{{end}}
  28.  
  29. {{range pipeline}} T1 {{end}}
  30. The value of the pipeline must be an array, slice, map, or channel.
  31. If the value of the pipeline has length zero, nothing is output;
  32. otherwise, dot is set to the successive elements of the array,
  33. slice, or map and T1 is executed. If the value is a map and the
  34. keys are of basic type with a defined order ("comparable"), the
  35. elements will be visited in sorted key order.
  36.  
  37. {{range pipeline}} T1 {{else}} T0 {{end}}
  38. The value of the pipeline must be an array, slice, map, or channel.
  39. If the value of the pipeline has length zero, dot is unaffected and
  40. T0 is executed; otherwise, dot is set to the successive elements
  41. of the array, slice, or map and T1 is executed.
  42.  
  43. {{template "name"}}
  44. The template with the specified name is executed with nil data.
  45.  
  46. {{template "name" pipeline}}
  47. The template with the specified name is executed with dot set
  48. to the value of the pipeline.
  49.  
  50. {{block "name" pipeline}} T1 {{end}}
  51. A block is shorthand for defining a template
  52. {{define "name"}} T1 {{end}}
  53. and then executing it in place
  54. {{template "name" pipeline}}
  55. The typical use is to define a set of root templates that are
  56. then customized by redefining the block templates within.
  57.  
  58. {{with pipeline}} T1 {{end}}
  59. If the value of the pipeline is empty, no output is generated;
  60. otherwise, dot is set to the value of the pipeline and T1 is
  61. executed.
  62.  
  63. {{with pipeline}} T1 {{else}} T0 {{end}}
  64. If the value of the pipeline is empty, dot is unaffected and T0
  65. is executed; otherwise, dot is set to the value of the pipeline
  66. and T1 is executed.

Arguments

An argument is a simple value, denoted by one of the following.

  1. - A boolean, string, character, integer, floating-point, imaginary
  2. or complex constant in Go syntax. These behave like Go's untyped
  3. constants.
  4. - The keyword nil, representing an untyped Go nil.
  5. - The character '.' (period):
  6. .
  7. The result is the value of dot.
  8. - A variable name, which is a (possibly empty) alphanumeric string
  9. preceded by a dollar sign, such as
  10. $piOver2
  11. or
  12. $
  13. The result is the value of the variable.
  14. Variables are described below.
  15. - The name of a field of the data, which must be a struct, preceded
  16. by a period, such as
  17. .Field
  18. The result is the value of the field. Field invocations may be
  19. chained:
  20. .Field1.Field2
  21. Fields can also be evaluated on variables, including chaining:
  22. $x.Field1.Field2
  23. - The name of a key of the data, which must be a map, preceded
  24. by a period, such as
  25. .Key
  26. The result is the map element value indexed by the key.
  27. Key invocations may be chained and combined with fields to any
  28. depth:
  29. .Field1.Key1.Field2.Key2
  30. Although the key must be an alphanumeric identifier, unlike with
  31. field names they do not need to start with an upper case letter.
  32. Keys can also be evaluated on variables, including chaining:
  33. $x.key1.key2
  34. - The name of a niladic method of the data, preceded by a period,
  35. such as
  36. .Method
  37. The result is the value of invoking the method with dot as the
  38. receiver, dot.Method(). Such a method must have one return value (of
  39. any type) or two return values, the second of which is an error.
  40. If it has two and the returned error is non-nil, execution terminates
  41. and an error is returned to the caller as the value of Execute.
  42. Method invocations may be chained and combined with fields and keys
  43. to any depth:
  44. .Field1.Key1.Method1.Field2.Key2.Method2
  45. Methods can also be evaluated on variables, including chaining:
  46. $x.Method1.Field
  47. - The name of a niladic function, such as
  48. fun
  49. The result is the value of invoking the function, fun(). The return
  50. types and values behave as in methods. Functions and function
  51. names are described below.
  52. - A parenthesized instance of one the above, for grouping. The result
  53. may be accessed by a field or map key invocation.
  54. print (.F1 arg1) (.F2 arg2)
  55. (.StructValuedMethod "arg").Field

Arguments may evaluate to any type; if they are pointers the implementation automatically indirects to the base type when required. If an evaluation yields a function value, such as a function-valued field of a struct, the function is not invoked automatically, but it can be used as a truth value for an if action and the like. To invoke it, use the call function, defined below.

Pipelines

A pipeline is a possibly chained sequence of "commands". A command is a simple value (argument) or a function or method call, possibly with multiple arguments:

  1. Argument
  2. The result is the value of evaluating the argument.
  3. .Method [Argument...]
  4. The method can be alone or the last element of a chain but,
  5. unlike methods in the middle of a chain, it can take arguments.
  6. The result is the value of calling the method with the
  7. arguments:
  8. dot.Method(Argument1, etc.)
  9. functionName [Argument...]
  10. The result is the value of calling the function associated
  11. with the name:
  12. function(Argument1, etc.)
  13. Functions and function names are described below.

A pipeline may be "chained" by separating a sequence of commands with pipeline characters '|'. In a chained pipeline, the result of each command is passed as the last argument of the following command. The output of the final command in the pipeline is the value of the pipeline.

The output of a command will be either one value or two values, the second of which has type error. If that second value is present and evaluates to non-nil, execution terminates and the error is returned to the caller of Execute.

Variables

A pipeline inside an action may initialize a variable to capture the result. The initialization has syntax

  1. $variable := pipeline

where $variable is the name of the variable. An action that declares a variable produces no output.

Variables previously declared can also be assigned, using the syntax

  1. $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:

  1. range $index, $element := pipeline

in which case $index and $element are set to the successive values of the array/slice index or map key and element, respectively. Note that if there is only one variable, it is assigned the element; this is opposite to the convention 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 if there is no such control structure. A template invocation does not inherit variables 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.

Examples

Here are some example one-line templates demonstrating pipelines and variables. All produce the quoted word "output":

  1. {{"\"output\""}}
  2. A string constant.
  3. {{`"output"`}}
  4. A raw string constant.
  5. {{printf "%q" "output"}}
  6. A function call.
  7. {{"output" | printf "%q"}}
  8. A function call whose final argument comes from the previous
  9. command.
  10. {{printf "%q" (print "out" "put")}}
  11. A parenthesized argument.
  12. {{"put" | printf "%s%s" "out" | printf "%q"}}
  13. A more elaborate call.
  14. {{"output" | printf "%s" | printf "%q"}}
  15. A longer chain.
  16. {{with "output"}}{{printf "%q" .}}{{end}}
  17. A with action using dot.
  18. {{with $x := "output" | printf "%q"}}{{$x}}{{end}}
  19. A with action that creates and uses a variable.
  20. {{with $x := "output"}}{{printf "%q" $x}}{{end}}
  21. A with action that uses the variable in another action.
  22. {{with $x := "output"}}{{$x | printf "%q"}}{{end}}
  23. The same, but pipelined.

Functions

During execution functions are found in two function maps: first in the template, then in the global function map. By default, no functions are defined in the template but the Funcs method can be used to add them.

Predefined global functions are named as follows.

  1. and
  2. Returns the boolean AND of its arguments by returning the
  3. first empty argument or the last argument, that is,
  4. "and x y" behaves as "if x then y else x". All the
  5. arguments are evaluated.
  6. call
  7. Returns the result of calling the first argument, which
  8. must be a function, with the remaining arguments as parameters.
  9. Thus "call .X.Y 1 2" is, in Go notation, dot.X.Y(1, 2) where
  10. Y is a func-valued field, map entry, or the like.
  11. The first argument must be the result of an evaluation
  12. that yields a value of function type (as distinct from
  13. a predefined function such as print). The function must
  14. return either one or two result values, the second of which
  15. is of type error. If the arguments don't match the function
  16. or the returned error value is non-nil, execution stops.
  17. html
  18. Returns the escaped HTML equivalent of the textual
  19. representation of its arguments. This function is unavailable
  20. in html/template, with a few exceptions.
  21. index
  22. Returns the result of indexing its first argument by the
  23. following arguments. Thus "index x 1 2 3" is, in Go syntax,
  24. x[1][2][3]. Each indexed item must be a map, slice, or array.
  25. js
  26. Returns the escaped JavaScript equivalent of the textual
  27. representation of its arguments.
  28. len
  29. Returns the integer length of its argument.
  30. not
  31. Returns the boolean negation of its single argument.
  32. or
  33. Returns the boolean OR of its arguments by returning the
  34. first non-empty argument or the last argument, that is,
  35. "or x y" behaves as "if x then x else y". All the
  36. arguments are evaluated.
  37. print
  38. An alias for fmt.Sprint
  39. printf
  40. An alias for fmt.Sprintf
  41. println
  42. An alias for fmt.Sprintln
  43. urlquery
  44. Returns the escaped value of the textual representation of
  45. its arguments in a form suitable for embedding in a URL query.
  46. This function is unavailable in html/template, with a few
  47. exceptions.

The boolean functions take any zero value to be false and a non-zero value to be true.

There is also a set of binary comparison operators defined as functions:

  1. eq
  2. Returns the boolean truth of arg1 == arg2
  3. ne
  4. Returns the boolean truth of arg1 != arg2
  5. lt
  6. Returns the boolean truth of arg1 < arg2
  7. le
  8. Returns the boolean truth of arg1 <= arg2
  9. gt
  10. Returns the boolean truth of arg1 > arg2
  11. ge
  12. Returns the boolean truth of arg1 >= arg2

For simpler multi-way equality tests, eq (only) accepts two or more arguments and compares the second and subsequent to the first, returning in effect

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

(Unlike with || in Go, however, eq is a function call and all the arguments will be evaluated.)

The comparison functions work on basic types only (or named basic types, such as "type Celsius float32"). They implement the Go rules for comparison of values, except that size and exact type are ignored, so any integer value, signed or unsigned, may be compared with any other integer value. (The arithmetic value is compared, not the bit pattern, so all negative integers are less than all unsigned integers.) However, as usual, one may not compare an int with a float32 and so on.

Associated templates

Each template is named by a string specified when it is created. Also, each template is associated with zero or more other templates that it may invoke by name; such associations are transitive and form a name space of templates.

A template may use a template invocation to instantiate another associated template; see the explanation of the "template" action above. The name must be that of a template associated with the template that contains the invocation.

Nested template definitions

When parsing a template, another template may be defined and associated with the template being parsed. Template definitions must appear at the top level of the template, 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 string constant. Here is a simple example:

  1. `{{define "T1"}}ONE{{end}}
  2. {{define "T2"}}TWO{{end}}
  3. {{define "T3"}}{{template "T1"}} {{template "T2"}}{{end}}
  4. {{template "T3"}}`

This defines two templates, T1 and T2, and a third T3 that invokes the other two when it is executed. Finally it invokes T3. If executed this template will produce the text

  1. ONE TWO

By construction, a template may reside in only one association. If it's necessary to have a template addressable from multiple associations, the template definition must be parsed multiple times to create distinct *Template values, or must be copied with the Clone or AddParseTree method.

Parse may be called multiple times to assemble the various associated templates; see the ParseFiles and ParseGlob functions and methods for simple ways to parse related templates stored in files.

A template may be executed directly or through ExecuteTemplate, which executes an associated template identified by name. To invoke our example above, we might write,

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

or to invoke a particular template explicitly by name,

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

Index

Examples

Package Files

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

func HTMLEscape

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

HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.

func HTMLEscapeString

  1. func HTMLEscapeString(s string) string

HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.

func HTMLEscaper

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

HTMLEscaper returns the escaped HTML equivalent of the textual representation of its arguments.

func IsTrue

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

IsTrue reports whether the value is 'true', in the sense of not the zero of its type, and whether the value has a meaningful truth value. This is the definition of truth used by if and other such actions.

func JSEscape

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

JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.

func JSEscapeString

  1. func JSEscapeString(s string) string

JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.

func JSEscaper

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

JSEscaper returns the escaped JavaScript equivalent of the textual representation of its arguments.

func URLQueryEscaper

  1. 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 ExecError

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

ExecError is the custom error type returned when Execute has an error evaluating its template. (If a write error occurs, the actual error is returned; it will not be of type ExecError.)

func (ExecError) Error

  1. func (e ExecError) Error() string

type FuncMap

  1. 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.

When template execution invokes a function with an argument list, that list must be assignable to the function's parameter types. Functions meant to apply to arguments of arbitrary type can use parameters of type interface{} or of type reflect.Value. Similarly, functions meant to return a result of arbitrary type can return interface{} or reflect.Value.

type Template

  1. type Template struct {
  2. *parse.Tree
  3. // contains filtered or unexported fields
  4. }

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.

func Must

  1. 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

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

func New

  1. func New(name string) *Template

New allocates a new, undefined template with the given name.

func ParseFiles

  1. 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.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results. For instance, ParseFiles("a/foo", "b/foo") stores "b/foo" as the template named "foo", while "a/foo" is unavailable.

func ParseGlob

  1. 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.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

func (*Template) AddParseTree

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

AddParseTree adds parse tree for template with given name and associates it with t. If the template does not already exist, it will create a new one. If the template does exist, it will be replaced.

func (*Template) Clone

  1. 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) DefinedTemplates

  1. func (t *Template) DefinedTemplates() string

DefinedTemplates returns a string listing the defined templates, prefixed by the string "; defined templates are: ". If there are none, it returns the empty string. For generating an error message here and in html/template.

func (*Template) Delims

  1. 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

  1. func (t *Template) Execute(wr io.Writer, data interface{}) 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, although if parallel executions share a Writer the output may be interleaved.

If data is a reflect.Value, the template applies to the concrete value that the reflect.Value holds, as in fmt.Print.

func (*Template) ExecuteTemplate

  1. 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, although if parallel executions share a Writer the output may be interleaved.

func (*Template) Funcs

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

Funcs adds the elements of the argument map to the template's function map. It must be called before the template is parsed. It panics if a value in the map is not a function with appropriate return type or if the name cannot be used syntactically as a function in a template. It is legal to overwrite elements of the map. The return value is the template, so calls can be chained.

func (*Template) Lookup

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

Lookup returns the template with the given name that is associated with t. It returns nil if there is no such template or the template has no definition.

func (*Template) Name

  1. func (t *Template) Name() string

Name returns the name of the template.

func (*Template) New

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

New allocates a new, undefined 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) Option

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

Option sets options for the template. Options are described by strings, either a simple string or "key=value". There can be at most one equals sign in an option string. If the option string is unrecognized or otherwise invalid, Option panics.

Known options:

missingkey: Control the behavior during execution if a map is indexed with a key that is not present in the map.

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

func (*Template) Parse

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

Parse parses text as a template body for t. Named template definitions ({{define ...}} or {{block ...}} statements) in text define additional templates associated with t and are removed from the definition of t itself.

Templates can be redefined in successive calls to Parse. A template definition with a body containing only white space and comments is considered empty and will not replace an existing template's body. This allows using Parse to add new named template definitions without overwriting the main template body.

func (*Template) ParseFiles

  1. 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. Since the templates created by ParseFiles are named by the base names of the argument files, t should usually have the name of one of the (base) names of the files. If it does not, depending on t's contents before calling ParseFiles, t.Execute may fail. In that case use t.ExecuteTemplate to execute a valid template.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

func (*Template) ParseGlob

  1. 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.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

func (*Template) Templates

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

Templates returns a slice of defined templates associated with t.

Directories

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

Package template imports 15 packages (graph) and is imported by 16358 packages. Updated 5 days ago.Refresh nowTools for package owners.

Go: text/templateIndex | Examples | Files | Directories

package template

import "text/template"

Package template implements data-driven templates for generating textual output.

To generate HTML output, see package html/template, which has the same interface as this package but automatically secures HTML output against certain attacks.

Templates are executed by applying them to a data structure. Annotations in the template refer to elements of the data structure (typically a field of a struct or 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, represented by a period '.' and called "dot", to the value at the current location in the structure 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. Except for raw strings, actions may not span newlines, although comments can.

Once parsed, a template may be executed safely in parallel, although if parallel executions share a Writer the output may be interleaved.

Here is a trivial example that prints "17 items are made of wool".

  1. type Inventory struct {
  2. Material string
  3. Count uint
  4. }
  5. sweaters := Inventory{"wool", 17}
  6. tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")
  7. if err != nil { panic(err) }
  8. err = tmpl.Execute(os.Stdout, sweaters)
  9. if err != nil { panic(err) }

More intricate examples appear below.

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.

However, to aid in formatting template source code, if an action's left delimiter (by default "{{") is followed immediately by a minus sign and ASCII space character ("{{- "), all trailing white space is trimmed from the immediately preceding text. Similarly, if the right delimiter ("}}") is preceded by a space and minus sign (" -}}"), all leading white space is trimmed from the immediately following text. In these trim markers, the ASCII space must be present; "{{-3}}" parses as an action containing the number -3.

For instance, when executing the template whose source is

  1. "{{23 -}} < {{- 45}}"

the generated output would be

  1. "23<45"

For this trimming, the definition of white space characters is the same as in Go: space, horizontal tab, carriage return, and newline.

Actions

Here is the list of actions. "Arguments" and "pipelines" are evaluations of data, defined in detail in the corresponding sections that follow.

  1. {{/* a comment */}}
  2. {{- /* a comment with white space trimmed from preceding and following text */ -}}
  3. A comment; discarded. May contain newlines.
  4. Comments do not nest and must start and end at the
  5. delimiters, as shown here.
  6.  
  7. {{pipeline}}
  8. The default textual representation (the same as would be
  9. printed by fmt.Print) of the value of the pipeline is copied
  10. to the output.
  11.  
  12. {{if pipeline}} T1 {{end}}
  13. If the value of the pipeline is empty, no output is generated;
  14. otherwise, T1 is executed. The empty values are false, 0, any
  15. nil pointer or interface value, and any array, slice, map, or
  16. string of length zero.
  17. Dot is unaffected.
  18.  
  19. {{if pipeline}} T1 {{else}} T0 {{end}}
  20. If the value of the pipeline is empty, T0 is executed;
  21. otherwise, T1 is executed. Dot is unaffected.
  22.  
  23. {{if pipeline}} T1 {{else if pipeline}} T0 {{end}}
  24. To simplify the appearance of if-else chains, the else action
  25. of an if may include another if directly; the effect is exactly
  26. the same as writing
  27. {{if pipeline}} T1 {{else}}{{if pipeline}} T0 {{end}}{{end}}
  28.  
  29. {{range pipeline}} T1 {{end}}
  30. The value of the pipeline must be an array, slice, map, or channel.
  31. If the value of the pipeline has length zero, nothing is output;
  32. otherwise, dot is set to the successive elements of the array,
  33. slice, or map and T1 is executed. If the value is a map and the
  34. keys are of basic type with a defined order ("comparable"), the
  35. elements will be visited in sorted key order.
  36.  
  37. {{range pipeline}} T1 {{else}} T0 {{end}}
  38. The value of the pipeline must be an array, slice, map, or channel.
  39. If the value of the pipeline has length zero, dot is unaffected and
  40. T0 is executed; otherwise, dot is set to the successive elements
  41. of the array, slice, or map and T1 is executed.
  42.  
  43. {{template "name"}}
  44. The template with the specified name is executed with nil data.
  45.  
  46. {{template "name" pipeline}}
  47. The template with the specified name is executed with dot set
  48. to the value of the pipeline.
  49.  
  50. {{block "name" pipeline}} T1 {{end}}
  51. A block is shorthand for defining a template
  52. {{define "name"}} T1 {{end}}
  53. and then executing it in place
  54. {{template "name" pipeline}}
  55. The typical use is to define a set of root templates that are
  56. then customized by redefining the block templates within.
  57.  
  58. {{with pipeline}} T1 {{end}}
  59. If the value of the pipeline is empty, no output is generated;
  60. otherwise, dot is set to the value of the pipeline and T1 is
  61. executed.
  62.  
  63. {{with pipeline}} T1 {{else}} T0 {{end}}
  64. If the value of the pipeline is empty, dot is unaffected and T0
  65. is executed; otherwise, dot is set to the value of the pipeline
  66. and T1 is executed.

Arguments

An argument is a simple value, denoted by one of the following.

  1. - A boolean, string, character, integer, floating-point, imaginary
  2. or complex constant in Go syntax. These behave like Go's untyped
  3. constants.
  4. - The keyword nil, representing an untyped Go nil.
  5. - The character '.' (period):
  6. .
  7. The result is the value of dot.
  8. - A variable name, which is a (possibly empty) alphanumeric string
  9. preceded by a dollar sign, such as
  10. $piOver2
  11. or
  12. $
  13. The result is the value of the variable.
  14. Variables are described below.
  15. - The name of a field of the data, which must be a struct, preceded
  16. by a period, such as
  17. .Field
  18. The result is the value of the field. Field invocations may be
  19. chained:
  20. .Field1.Field2
  21. Fields can also be evaluated on variables, including chaining:
  22. $x.Field1.Field2
  23. - The name of a key of the data, which must be a map, preceded
  24. by a period, such as
  25. .Key
  26. The result is the map element value indexed by the key.
  27. Key invocations may be chained and combined with fields to any
  28. depth:
  29. .Field1.Key1.Field2.Key2
  30. Although the key must be an alphanumeric identifier, unlike with
  31. field names they do not need to start with an upper case letter.
  32. Keys can also be evaluated on variables, including chaining:
  33. $x.key1.key2
  34. - The name of a niladic method of the data, preceded by a period,
  35. such as
  36. .Method
  37. The result is the value of invoking the method with dot as the
  38. receiver, dot.Method(). Such a method must have one return value (of
  39. any type) or two return values, the second of which is an error.
  40. If it has two and the returned error is non-nil, execution terminates
  41. and an error is returned to the caller as the value of Execute.
  42. Method invocations may be chained and combined with fields and keys
  43. to any depth:
  44. .Field1.Key1.Method1.Field2.Key2.Method2
  45. Methods can also be evaluated on variables, including chaining:
  46. $x.Method1.Field
  47. - The name of a niladic function, such as
  48. fun
  49. The result is the value of invoking the function, fun(). The return
  50. types and values behave as in methods. Functions and function
  51. names are described below.
  52. - A parenthesized instance of one the above, for grouping. The result
  53. may be accessed by a field or map key invocation.
  54. print (.F1 arg1) (.F2 arg2)
  55. (.StructValuedMethod "arg").Field

Arguments may evaluate to any type; if they are pointers the implementation automatically indirects to the base type when required. If an evaluation yields a function value, such as a function-valued field of a struct, the function is not invoked automatically, but it can be used as a truth value for an if action and the like. To invoke it, use the call function, defined below.

Pipelines

A pipeline is a possibly chained sequence of "commands". A command is a simple value (argument) or a function or method call, possibly with multiple arguments:

  1. Argument
  2. The result is the value of evaluating the argument.
  3. .Method [Argument...]
  4. The method can be alone or the last element of a chain but,
  5. unlike methods in the middle of a chain, it can take arguments.
  6. The result is the value of calling the method with the
  7. arguments:
  8. dot.Method(Argument1, etc.)
  9. functionName [Argument...]
  10. The result is the value of calling the function associated
  11. with the name:
  12. function(Argument1, etc.)
  13. Functions and function names are described below.

A pipeline may be "chained" by separating a sequence of commands with pipeline characters '|'. In a chained pipeline, the result of each command is passed as the last argument of the following command. The output of the final command in the pipeline is the value of the pipeline.

The output of a command will be either one value or two values, the second of which has type error. If that second value is present and evaluates to non-nil, execution terminates and the error is returned to the caller of Execute.

Variables

A pipeline inside an action may initialize a variable to capture the result. The initialization has syntax

  1. $variable := pipeline

where $variable is the name of the variable. An action that declares a variable produces no output.

Variables previously declared can also be assigned, using the syntax

  1. $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:

  1. range $index, $element := pipeline

in which case $index and $element are set to the successive values of the array/slice index or map key and element, respectively. Note that if there is only one variable, it is assigned the element; this is opposite to the convention 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 if there is no such control structure. A template invocation does not inherit variables 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.

Examples

Here are some example one-line templates demonstrating pipelines and variables. All produce the quoted word "output":

  1. {{"\"output\""}}
  2. A string constant.
  3. {{`"output"`}}
  4. A raw string constant.
  5. {{printf "%q" "output"}}
  6. A function call.
  7. {{"output" | printf "%q"}}
  8. A function call whose final argument comes from the previous
  9. command.
  10. {{printf "%q" (print "out" "put")}}
  11. A parenthesized argument.
  12. {{"put" | printf "%s%s" "out" | printf "%q"}}
  13. A more elaborate call.
  14. {{"output" | printf "%s" | printf "%q"}}
  15. A longer chain.
  16. {{with "output"}}{{printf "%q" .}}{{end}}
  17. A with action using dot.
  18. {{with $x := "output" | printf "%q"}}{{$x}}{{end}}
  19. A with action that creates and uses a variable.
  20. {{with $x := "output"}}{{printf "%q" $x}}{{end}}
  21. A with action that uses the variable in another action.
  22. {{with $x := "output"}}{{$x | printf "%q"}}{{end}}
  23. The same, but pipelined.

Functions

During execution functions are found in two function maps: first in the template, then in the global function map. By default, no functions are defined in the template but the Funcs method can be used to add them.

Predefined global functions are named as follows.

  1. and
  2. Returns the boolean AND of its arguments by returning the
  3. first empty argument or the last argument, that is,
  4. "and x y" behaves as "if x then y else x". All the
  5. arguments are evaluated.
  6. call
  7. Returns the result of calling the first argument, which
  8. must be a function, with the remaining arguments as parameters.
  9. Thus "call .X.Y 1 2" is, in Go notation, dot.X.Y(1, 2) where
  10. Y is a func-valued field, map entry, or the like.
  11. The first argument must be the result of an evaluation
  12. that yields a value of function type (as distinct from
  13. a predefined function such as print). The function must
  14. return either one or two result values, the second of which
  15. is of type error. If the arguments don't match the function
  16. or the returned error value is non-nil, execution stops.
  17. html
  18. Returns the escaped HTML equivalent of the textual
  19. representation of its arguments. This function is unavailable
  20. in html/template, with a few exceptions.
  21. index
  22. Returns the result of indexing its first argument by the
  23. following arguments. Thus "index x 1 2 3" is, in Go syntax,
  24. x[1][2][3]. Each indexed item must be a map, slice, or array.
  25. js
  26. Returns the escaped JavaScript equivalent of the textual
  27. representation of its arguments.
  28. len
  29. Returns the integer length of its argument.
  30. not
  31. Returns the boolean negation of its single argument.
  32. or
  33. Returns the boolean OR of its arguments by returning the
  34. first non-empty argument or the last argument, that is,
  35. "or x y" behaves as "if x then x else y". All the
  36. arguments are evaluated.
  37. print
  38. An alias for fmt.Sprint
  39. printf
  40. An alias for fmt.Sprintf
  41. println
  42. An alias for fmt.Sprintln
  43. urlquery
  44. Returns the escaped value of the textual representation of
  45. its arguments in a form suitable for embedding in a URL query.
  46. This function is unavailable in html/template, with a few
  47. exceptions.

The boolean functions take any zero value to be false and a non-zero value to be true.

There is also a set of binary comparison operators defined as functions:

  1. eq
  2. Returns the boolean truth of arg1 == arg2
  3. ne
  4. Returns the boolean truth of arg1 != arg2
  5. lt
  6. Returns the boolean truth of arg1 < arg2
  7. le
  8. Returns the boolean truth of arg1 <= arg2
  9. gt
  10. Returns the boolean truth of arg1 > arg2
  11. ge
  12. Returns the boolean truth of arg1 >= arg2

For simpler multi-way equality tests, eq (only) accepts two or more arguments and compares the second and subsequent to the first, returning in effect

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

(Unlike with || in Go, however, eq is a function call and all the arguments will be evaluated.)

The comparison functions work on basic types only (or named basic types, such as "type Celsius float32"). They implement the Go rules for comparison of values, except that size and exact type are ignored, so any integer value, signed or unsigned, may be compared with any other integer value. (The arithmetic value is compared, not the bit pattern, so all negative integers are less than all unsigned integers.) However, as usual, one may not compare an int with a float32 and so on.

Associated templates

Each template is named by a string specified when it is created. Also, each template is associated with zero or more other templates that it may invoke by name; such associations are transitive and form a name space of templates.

A template may use a template invocation to instantiate another associated template; see the explanation of the "template" action above. The name must be that of a template associated with the template that contains the invocation.

Nested template definitions

When parsing a template, another template may be defined and associated with the template being parsed. Template definitions must appear at the top level of the template, 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 string constant. Here is a simple example:

  1. `{{define "T1"}}ONE{{end}}
  2. {{define "T2"}}TWO{{end}}
  3. {{define "T3"}}{{template "T1"}} {{template "T2"}}{{end}}
  4. {{template "T3"}}`

This defines two templates, T1 and T2, and a third T3 that invokes the other two when it is executed. Finally it invokes T3. If executed this template will produce the text

  1. ONE TWO

By construction, a template may reside in only one association. If it's necessary to have a template addressable from multiple associations, the template definition must be parsed multiple times to create distinct *Template values, or must be copied with the Clone or AddParseTree method.

Parse may be called multiple times to assemble the various associated templates; see the ParseFiles and ParseGlob functions and methods for simple ways to parse related templates stored in files.

A template may be executed directly or through ExecuteTemplate, which executes an associated template identified by name. To invoke our example above, we might write,

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

or to invoke a particular template explicitly by name,

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

Index

Examples

Package Files

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

func HTMLEscape

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

HTMLEscape writes to w the escaped HTML equivalent of the plain text data b.

func HTMLEscapeString

  1. func HTMLEscapeString(s string) string

HTMLEscapeString returns the escaped HTML equivalent of the plain text data s.

func HTMLEscaper

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

HTMLEscaper returns the escaped HTML equivalent of the textual representation of its arguments.

func IsTrue

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

IsTrue reports whether the value is 'true', in the sense of not the zero of its type, and whether the value has a meaningful truth value. This is the definition of truth used by if and other such actions.

func JSEscape

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

JSEscape writes to w the escaped JavaScript equivalent of the plain text data b.

func JSEscapeString

  1. func JSEscapeString(s string) string

JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.

func JSEscaper

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

JSEscaper returns the escaped JavaScript equivalent of the textual representation of its arguments.

func URLQueryEscaper

  1. 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 ExecError

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

ExecError is the custom error type returned when Execute has an error evaluating its template. (If a write error occurs, the actual error is returned; it will not be of type ExecError.)

func (ExecError) Error

  1. func (e ExecError) Error() string

type FuncMap

  1. 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.

When template execution invokes a function with an argument list, that list must be assignable to the function's parameter types. Functions meant to apply to arguments of arbitrary type can use parameters of type interface{} or of type reflect.Value. Similarly, functions meant to return a result of arbitrary type can return interface{} or reflect.Value.

type Template

  1. type Template struct {
  2. *parse.Tree
  3. // contains filtered or unexported fields
  4. }

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.

func Must

  1. 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

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

func New

  1. func New(name string) *Template

New allocates a new, undefined template with the given name.

func ParseFiles

  1. 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.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results. For instance, ParseFiles("a/foo", "b/foo") stores "b/foo" as the template named "foo", while "a/foo" is unavailable.

func ParseGlob

  1. 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.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

func (*Template) AddParseTree

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

AddParseTree adds parse tree for template with given name and associates it with t. If the template does not already exist, it will create a new one. If the template does exist, it will be replaced.

func (*Template) Clone

  1. 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) DefinedTemplates

  1. func (t *Template) DefinedTemplates() string

DefinedTemplates returns a string listing the defined templates, prefixed by the string "; defined templates are: ". If there are none, it returns the empty string. For generating an error message here and in html/template.

func (*Template) Delims

  1. 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

  1. func (t *Template) Execute(wr io.Writer, data interface{}) 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, although if parallel executions share a Writer the output may be interleaved.

If data is a reflect.Value, the template applies to the concrete value that the reflect.Value holds, as in fmt.Print.

func (*Template) ExecuteTemplate

  1. 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, although if parallel executions share a Writer the output may be interleaved.

func (*Template) Funcs

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

Funcs adds the elements of the argument map to the template's function map. It must be called before the template is parsed. It panics if a value in the map is not a function with appropriate return type or if the name cannot be used syntactically as a function in a template. It is legal to overwrite elements of the map. The return value is the template, so calls can be chained.

func (*Template) Lookup

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

Lookup returns the template with the given name that is associated with t. It returns nil if there is no such template or the template has no definition.

func (*Template) Name

  1. func (t *Template) Name() string

Name returns the name of the template.

func (*Template) New

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

New allocates a new, undefined 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) Option

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

Option sets options for the template. Options are described by strings, either a simple string or "key=value". There can be at most one equals sign in an option string. If the option string is unrecognized or otherwise invalid, Option panics.

Known options:

missingkey: Control the behavior during execution if a map is indexed with a key that is not present in the map.

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

func (*Template) Parse

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

Parse parses text as a template body for t. Named template definitions ({{define ...}} or {{block ...}} statements) in text define additional templates associated with t and are removed from the definition of t itself.

Templates can be redefined in successive calls to Parse. A template definition with a body containing only white space and comments is considered empty and will not replace an existing template's body. This allows using Parse to add new named template definitions without overwriting the main template body.

func (*Template) ParseFiles

  1. 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. Since the templates created by ParseFiles are named by the base names of the argument files, t should usually have the name of one of the (base) names of the files. If it does not, depending on t's contents before calling ParseFiles, t.Execute may fail. In that case use t.ExecuteTemplate to execute a valid template.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

func (*Template) ParseGlob

  1. 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.

When parsing multiple files with the same name in different directories, the last one mentioned will be the one that results.

func (*Template) Templates

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

Templates returns a slice of defined templates associated with t.

Directories

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

Package template imports 15 packages (graph) and is imported by 16358 packages. Updated 5 days ago.Refresh nowTools for package owners.

Package template (html/template) ... Types HTML, JS, URL, and others from content.go can carry safe content that is exempted from escaping. ... (*Template) Funcs ..的更多相关文章

  1. 【转】关于URL编码/javascript/js url 编码/url的三个js编码函数

    来源:http://www.cnblogs.com/huzi007/p/4174519.html 关于URL编码/javascript/js url 编码/url的三个js编码函数escape(),e ...

  2. JS URL编码

    JS URL编码escape() 方法: 采用ISO Latin字符集对指定的字符串进行编码.所有的空格符.标点符号.特殊字符以及其他非ASCII字符都将被转化成%xx格式的字符编码(xx等于该字符在 ...

  3. 关于URL编码/javascript/js url 编码/url的三个js编码函数

    关于URL编码/javascript/js url 编码/url的三个js编码函数escape(),encodeURI(),encodeURIComponent() 本文为您讲述关于js(javasc ...

  4. js url传值中文乱码完美解决(JAVA)

    js url传值中文乱码完美解决(JAVA) 首先在你的jsp页面这样更改: var url="你要传入的Action的位置&ipid="+ipid+"& ...

  5. 为什么返回的数据前面有callback? ashx/json.ashx?的后面加 callback=? 起什么作用 js url?callback=xxx xxx的介绍 ajax 跨域请求时url参数添加callback=?会实现跨域问题

    为什么返回的数据前面有callback?   这是一个同学出现的问题,问到了我. 应该是这样的: 但问题是这样的: 我看了所请求的格式和后台要求的也是相同的.而且我也是这种做法,为什么他的就不行呢? ...

  6. js URL中文传参乱码

    js: var searchVal = encodeURIComponent($.trim($('#js_search_val').val()));//搜索的值 encodeURIComponent( ...

  7. JS URL传中文参数引发的乱码问题

    今天的项目中碰到了一个乱码问题,从JS里传URL到服务器,URL中有中文参数,服务器里读出的中文参数来的全是“?”,查了网上JS编码相关资料得以解决. 解决方法一: 1.在JS里对中文参数进行两次转码 ...

  8. C# JS URL 中文传参出现乱码的解决方法

    在传参是先编码在传输,接受时先编码,在接收. string mm=Server.URLEncode(你); Response.Redirect(index.aspx?mm=+mm); 然后在接收页解码 ...

  9. js url传值中文乱码之解决之道

    在websphere 中使用的是url=encodeURI(encodeURI(url)); //用了2次encodeURI 测试成功,第一次转换没有尝试, 处理方法一. js 程序代码:url=en ...

随机推荐

  1. 机器人操作系统ROS Indigo 入门学习(1)——安装ROS Indigo【转】

    转自:http://blog.csdn.net/bobsweetie/article/details/43638761 Ubuntu14.04安装ROS Indigo 一.安装ROS 1.1配置Ubu ...

  2. 解决Ubuntu系统中文乱码显示问题

    sudo dpkg-reconfigure locales最后重启ubuntu. 重启后在系统设置--语言设置里面需要勾选中文,就会自动下载中文包,安装完成后再次重启就ok了.

  3. hdu 4514(树的直径+并查集)

    湫湫系列故事——设计风景线 Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)Tot ...

  4. Java 实现随机验证码

    许多系统的注册.登录或者发布信息模块都添加的随机码功能,就是为了避免自动注册程序或者自动发布程序的使用. 验证码实际上就是随机选择一些字符以图片的形式展现在页面上,如果进行提交操作的同时需要将图片上的 ...

  5. IDEA重新打jar包时报错MANIFEST.MF already exists in VFS

    报错原因:曾经打过jar包了,把之前的包删掉无用,VFS:虚拟文件系统.即使删掉之前的包,信息依然会在此处.故删掉MANIFEST文件夹,重新打包即可解决.

  6. python中执行shell命令的几个方法

    1.os.system() a=os.system("df -hT | awk 'NR==3{print $(NF-1)}'") 该命令会在页面上打印输出结果,但变量不会保留结果, ...

  7. 在spring中使用数据库

    若要在spring中使用数据库,首先需要配置数据源. 1.使用数据源连接池,可以使用DBCP(Data Base Connection Pooling) <bean id="datas ...

  8. springboot 启动类启动跳转到前端网页404问题的两个解决方案

    前段时间研究springboot 发现使用Application类启动的话, 可以进入Controller方法并且返回数据,但是不能跳转到WEB-INF目录下网页, 前置配置 server: port ...

  9. commons-lang3-RandomUtils

    随机工具类   RandomUtils nextBoolean() 返回一个随机boolean值 nextBytes(int count) 返回一个指定大小的随机byte数组 nextDouble() ...

  10. [Algorithm] Write a Depth First Search Algorithm for Graphs in JavaScript

    Depth first search is a graph search algorithm that starts at one node and uses recursion to travel ...