template

package
v0.0.0-...-9caa667 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 12, 2014 License: GPL-2.0, BSD-3-Clause Imports: 9 Imported by: 0

Documentation

Overview

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

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. The template walks the structure as it executes and the "cursor" @ represents the value at the current location in the structure.

Data items may be values or pointers; the interface hides the indirection.

In the following, 'Field' is one of several things, according to the data.

  • The name of a field of a struct (result = data.Field),
  • The value stored in a map under that key (result = data["Field"]), or
  • The result of invoking a niladic single-valued method with that name (result = data.Field())

If Field is a struct field or method name, it must be an exported (capitalized) name.

Major constructs ({} are the default delimiters for template actions; [] are the notation in this comment for optional elements):

{# comment }

A one-line comment.

{.section field} XXX [ {.or} YYY ] {.end}

Set @ to the value of the field. It may be an explicit @ to stay at the same point in the data. If the field is nil or empty, execute YYY; otherwise execute XXX.

{.repeated section field} XXX [ {.alternates with} ZZZ ] [ {.or} YYY ] {.end}

Like .section, but field must be an array or slice. XXX is executed for each element. If the array is nil or empty, YYY is executed instead. If the {.alternates with} marker is present, ZZZ is executed between iterations of XXX.

{field}
{field1 field2 ...}
{field|formatter}
{field1 field2...|formatter}
{field|formatter1|formatter2}

Insert the value of the fields into the output. Each field is first looked for in the cursor, as in .section and .repeated. If it is not found, the search continues in outer sections until the top level is reached.

If the field value is a pointer, leading asterisks indicate that the value to be inserted should be evaluated through the pointer. For example, if x.p is of type *int, {x.p} will insert the value of the pointer but {*x.p} will insert the value of the underlying integer. If the value is nil or not a pointer, asterisks have no effect.

If a formatter is specified, it must be named in the formatter map passed to the template set up routines or in the default set ("html","str","") and is used to process the data for output. The formatter function has signature

func(wr io.Writer, formatter string, data ...interface{})

where wr is the destination for output, data holds the field values at the instantiation, and formatter is its name at the invocation site. The default formatter just concatenates the string representations of the fields.

Multiple formatters separated by the pipeline character | are executed sequentially, with each formatter receiving the bytes emitted by the one to its left.

As well as field names, one may use literals with Go syntax. Integer, floating-point, and string literals are supported. Raw strings may not span newlines.

The delimiter strings get their default value, "{" and "}", from JSON-template. They may be set to any non-empty, space-free string using the SetDelims method. Their value can be printed in the output using {.meta-left} and {.meta-right}.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HTMLEscape

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

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

func HTMLFormatter

func HTMLFormatter(w io.Writer, format string, value ...interface{})

HTMLFormatter formats arbitrary values for HTML

func StringFormatter

func StringFormatter(w io.Writer, format string, value ...interface{})

StringFormatter formats into the default string representation. It is stored under the name "str" and is the default formatter. You can override the default formatter by storing your default under the name "" in your custom formatter map.

Types

type Error

type Error struct {
	Line int
	Msg  string
}

Errors returned during parsing and execution. Users may extract the information and reformat if they desire.

func (*Error) Error

func (e *Error) Error() string

type FormatterMap

type FormatterMap map[string]func(io.Writer, string, ...interface{})

FormatterMap is the type describing the mapping from formatter names to the functions that implement them.

type Template

type Template struct {
	// contains filtered or unexported fields
}

Template is the type that represents a template definition. It is unchanged after parsing.

func MustParse

func MustParse(s string, fmap FormatterMap) *Template

MustParse is like Parse but panics if the template cannot be parsed.

func MustParseFile

func MustParseFile(filename string, fmap FormatterMap) *Template

MustParseFile is like ParseFile but panics if the file cannot be read or the template cannot be parsed.

func New

func New(fmap FormatterMap) *Template

New creates a new template with the specified formatter map (which may be nil) to define auxiliary functions for formatting variables.

func Parse

func Parse(s string, fmap FormatterMap) (t *Template, err error)

Parse creates a Template with default parameters (such as {} for metacharacters). The string s contains the template text while the formatter map fmap, which may be nil, defines auxiliary functions for formatting variables. The template is returned. If any errors occur, err will be non-nil.

func ParseFile

func ParseFile(filename string, fmap FormatterMap) (t *Template, err error)

ParseFile is a wrapper function that creates a Template with default parameters (such as {} for metacharacters). The filename identifies a file containing the template text, while the formatter map fmap, which may be nil, defines auxiliary functions for formatting variables. The template is returned. If any errors occur, err will be non-nil.

func (*Template) Execute

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

Execute applies a parsed template to the specified data object, generating output to wr.

func (*Template) Parse

func (t *Template) Parse(s string) (err error)

Parse initializes a Template by parsing its definition. The string s contains the template text. If any errors occur, Parse returns the error.

func (*Template) ParseFile

func (t *Template) ParseFile(filename string) (err error)

ParseFile is like Parse but reads the template definition from the named file.

func (*Template) SetDelims

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

SetDelims sets the left and right delimiters for operations in the template. They are validated during parsing. They could be validated here but it's better to keep the routine simple. The delimiters are very rarely invalid and Parse has the necessary error-handling interface already.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL