README
¶
Mustache Template Engine for Go
Why a Fork?
I forked hoisie/mustache because it does not appear to be maintained, and I wanted to add the following functionality:
- Update the API to follow the idiomatic Go convention of returning errors (this is a breaking change)
- Add option to treat missing variables as errors
CLI Overview
➜ ~ go get github.com/cbroglie/mustache/...
➜ ~ mustache
Usage:
mustache [data] template [flags]
Examples:
$ mustache data.yml template.mustache
$ cat data.yml | mustache template.mustache
Flags:
-h, --help help for mustache
➜ ~
Package Overview
This library is an implementation of the Mustache template language in Go.
Mustache Spec Compliance
mustache/spec contains the formal standard for Mustache, and it is included as a submodule (using v1.1.3) for testing compliance. All of the tests pass (big thanks to kei10in), though the optional lambda support has not been implemented.
Documentation
For more information about mustache, check out the mustache project page or the mustache manual.
Also check out some example mustache files
Installation
To install mustache.go, simply run go get github.com/cbroglie/mustache
. To use it in a program, use import "github.com/cbroglie/mustache"
Usage
There are four main methods in this package:
Render(data string, context ...interface{}) (string, error)
RenderFile(filename string, context ...interface{}) (string, error)
ParseString(data string) (*Template, error)
ParseFile(filename string) (*Template, error)
There are also two additional methods for using layouts (explained below); as well as several more that can provide a custom Partial retrieval.
The Render method takes a string and a data source, which is generally a map or struct, and returns the output string. If the template file contains an error, the return value is a description of the error. There's a similar method, RenderFile, which takes a filename as an argument and uses that for the template contents.
data, err := mustache.Render("hello {{c}}", map[string]string{"c": "world"})
If you're planning to render the same template multiple times, you do it efficiently by compiling the template first:
tmpl, _ := mustache.ParseString("hello {{c}}")
var buf bytes.Buffer
for i := 0; i < 10; i++ {
tmpl.FRender(&buf, map[string]string{"c": "world"})
}
For more example usage, please see mustache_test.go
Escaping
mustache.go follows the official mustache HTML escaping rules. That is, if you enclose a variable with two curly brackets, {{var}}
, the contents are HTML-escaped. For instance, strings like 5 > 2
are converted to 5 > 2
. To use raw characters, use three curly brackets {{{var}}}
.
Layouts
It is a common pattern to include a template file as a "wrapper" for other templates. The wrapper may include a header and a footer, for instance. Mustache.go supports this pattern with the following two methods:
RenderInLayout(data string, layout string, context ...interface{}) (string, error)
RenderFileInLayout(filename string, layoutFile string, context ...interface{}) (string, error)
The layout file must have a variable called {{content}}
. For example, given the following files:
layout.html.mustache:
<html>
<head><title>Hi</title></head>
<body>
{{{content}}}
</body>
</html>
template.html.mustache:
<h1>Hello World!</h1>
A call to RenderFileInLayout("template.html.mustache", "layout.html.mustache", nil)
will produce:
<html>
<head><title>Hi</title></head>
<body>
<h1>Hello World!</h1>
</body>
</html>
Custom PartialProvider
Mustache.go has been extended to support a user-defined repository for mustache partials, instead of the default of requiring file-based templates.
Several new top-level functions have been introduced to take advantage of this:
func RenderPartials(data string, partials PartialProvider, context ...interface{}) (string, error)
func RenderInLayoutPartials(data string, layoutData string, partials PartialProvider, context ...interface{}) (string, error)
func ParseStringPartials(data string, partials PartialProvider) (*Template, error)
func ParseFilePartials(filename string, partials PartialProvider) (*Template, error)
A PartialProvider
is any object that responds to Get(string) (*Template,error)
, and two examples are provided- a FileProvider
that
recreates the old behavior (and is indeed used internally for backwards
compatibility); and a StaticProvider
alias for a map[string]string
. Using
either of these is simple:
fp := &FileProvider{
Paths: []string{ "", "/opt/mustache", "templates/" },
Extensions: []string{ "", ".stache", ".mustache" },
}
tmpl, err := ParseStringPartials("This partial is loaded from a file: {{>foo}}", fp)
sp := StaticProvider(map[string]string{
"foo": "{{>bar}}",
"bar": "some data",
})
tmpl, err := ParseStringPartials("This partial is loaded from a map: {{>foo}}", sp)
A note about method receivers
Mustache.go supports calling methods on objects, but you have to be aware of Go's limitations. For example, lets's say you have the following type:
type Person struct {
FirstName string
LastName string
}
func (p *Person) Name1() string {
return p.FirstName + " " + p.LastName
}
func (p Person) Name2() string {
return p.FirstName + " " + p.LastName
}
While they appear to be identical methods, Name1
has a pointer receiver, and Name2
has a value receiver. Objects of type Person
(non-pointer) can only access Name2
, while objects of type *Person
(person) can access both. This is by design in the Go language.
So if you write the following:
mustache.Render("{{Name1}}", Person{"John", "Smith"})
It'll be blank. You either have to use &Person{"John", "Smith"}
, or call Name2
Supported features
- Variables
- Comments
- Change delimiter
- Sections (boolean, enumerable, and inverted)
- Partials
Documentation
¶
Index ¶
- Constants
- Variables
- func Render(data string, context ...interface{}) (string, error)
- func RenderFile(filename string, context ...interface{}) (string, error)
- func RenderFileInLayout(filename string, layoutFile string, context ...interface{}) (string, error)
- func RenderInLayout(data string, layoutData string, context ...interface{}) (string, error)
- func RenderInLayoutPartials(data string, layoutData string, partials PartialProvider, ...) (string, error)
- func RenderPartials(data string, partials PartialProvider, context ...interface{}) (string, error)
- func RenderPartialsRaw(data string, partials PartialProvider, forceRaw bool, context ...interface{}) (string, error)
- func RenderRaw(data string, forceRaw bool, context ...interface{}) (string, error)
- type FileProvider
- type PartialProvider
- type StaticProvider
- type Tag
- type TagType
- type Template
- func ParseFile(filename string) (*Template, error)
- func ParseFilePartials(filename string, partials PartialProvider) (*Template, error)
- func ParseFilePartialsRaw(filename string, forceRaw bool, partials PartialProvider) (*Template, error)
- func ParseString(data string) (*Template, error)
- func ParseStringPartials(data string, partials PartialProvider) (*Template, error)
- func ParseStringPartialsRaw(data string, partials PartialProvider, forceRaw bool) (*Template, error)
- func ParseStringRaw(data string, forceRaw bool) (*Template, error)
- func (tmpl *Template) FRender(out io.Writer, context ...interface{}) error
- func (tmpl *Template) FRenderInLayout(out io.Writer, layout *Template, context ...interface{}) error
- func (tmpl *Template) Render(context ...interface{}) (string, error)
- func (tmpl *Template) RenderInLayout(layout *Template, context ...interface{}) (string, error)
- func (tmpl *Template) Tags() []Tag
Constants ¶
const (
SkipWhitespaceTagTypes = "#^/<>=!"
)
Skip all whitespaces apeared after these types of tags until end of line if the line only contains a tag and whitespaces.
Variables ¶
var ( // AllowMissingVariables defines the behavior for a variable "miss." If it // is true (the default), an empty string is emitted. If it is false, an error // is generated instead. AllowMissingVariables = true )
Functions ¶
func Render ¶
Render compiles a mustache template string and uses the the given data source - generally a map or struct - to render the template and return the output.
func RenderFile ¶
RenderFile loads a mustache template string from a file and compiles it, and then uses the the given data source - generally a map or struct - to render the template and return the output.
func RenderFileInLayout ¶
RenderFileInLayout loads a mustache template string and layout "wrapper" template string from files and compiles them, and then uses the the given data source - generally a map or struct - to render the compiled templates and return the output.
func RenderInLayout ¶
RenderInLayout compiles a mustache template string and layout "wrapper" and uses the given data source - generally a map or struct - to render the compiled templates and return the output.
func RenderInLayoutPartials ¶
func RenderInLayoutPartials(data string, layoutData string, partials PartialProvider, context ...interface{}) (string, error)
func RenderPartials ¶
func RenderPartials(data string, partials PartialProvider, context ...interface{}) (string, error)
RenderPartials compiles a mustache template string and uses the the given partial provider and data source - generally a map or struct - to render the template and return the output.
func RenderPartialsRaw ¶
func RenderPartialsRaw(data string, partials PartialProvider, forceRaw bool, context ...interface{}) (string, error)
Types ¶
type FileProvider ¶
FileProvider implements the PartialProvider interface by providing partials drawn from a filesystem. When a partial named `NAME` is requested, FileProvider searches each listed path for a file named as `NAME` followed by any of the listed extensions. The default for `Paths` is to search the current working directory. The default for `Extensions` is to examine, in order, no extension; then ".mustache"; then ".stache".
type PartialProvider ¶
type PartialProvider interface { // Get accepts the name of a partial and returns the parsed partial, if it could be found; a valid but empty // template, if it could not be found; or nil and error if an error occurred (other than an inability to find // the partial). Get(name string) (string, error) }
PartialProvider comprises the behaviors required of a struct to be able to provide partials to the mustache rendering engine.
type StaticProvider ¶
StaticProvider implements the PartialProvider interface by providing partials drawn from a map, which maps partial name to template contents.
type Tag ¶
type Tag interface { // Type returns the type of the tag. Type() TagType // Name returns the name of the tag. Name() string // Tags returns any child tags. It panics for tag types which cannot contain // child tags (i.e. variable tags). Tags() []Tag }
Tag represents the different mustache tag types.
Not all methods apply to all kinds of tags. Restrictions, if any, are noted in the documentation for each method. Use the Type method to find out the type of tag before calling type-specific methods. Calling a method inappropriate to the type of tag causes a run time panic.
type TagType ¶
type TagType uint
A TagType represents the specific type of mustache tag that a Tag represents. The zero TagType is not a valid type.
Defines representing the possible Tag types
type Template ¶
type Template struct {
// contains filtered or unexported fields
}
Template represents a compilde mustache template
func ParseFile ¶
ParseFile loads a mustache template string from a file and compiles it. The resulting output can be used to efficiently render the template multiple times with different data sources.
func ParseFilePartials ¶
func ParseFilePartials(filename string, partials PartialProvider) (*Template, error)
ParseFilePartials loads a mustache template string from a file, retrieving any required partials from the given provider, and compiles it. The resulting output can be used to efficiently render the template multiple times with different data sources.
func ParseFilePartialsRaw ¶
func ParseFilePartialsRaw(filename string, forceRaw bool, partials PartialProvider) (*Template, error)
func ParseString ¶
ParseString compiles a mustache template string. The resulting output can be used to efficiently render the template multiple times with different data sources.
func ParseStringPartials ¶
func ParseStringPartials(data string, partials PartialProvider) (*Template, error)
ParseStringPartials compiles a mustache template string, retrieving any required partials from the given provider. The resulting output can be used to efficiently render the template multiple times with different data sources.
func ParseStringPartialsRaw ¶
func ParseStringPartialsRaw(data string, partials PartialProvider, forceRaw bool) (*Template, error)
func (*Template) FRender ¶
FRender uses the given data source - generally a map or struct - to render the compiled template to an io.Writer.
func (*Template) FRenderInLayout ¶
func (tmpl *Template) FRenderInLayout(out io.Writer, layout *Template, context ...interface{}) error
FRenderInLayout uses the given data source - generally a map or struct - to render the compiled templated a loayout "wrapper" template to an io.Writer.
func (*Template) Render ¶
Render uses the given data source - generally a map or struct - to render the compiled template and return the output.
func (*Template) RenderInLayout ¶
RenderInLayout uses the given data source - generally a map or struct - to render the compiled template and layout "wrapper" template and return the output.