raymond: github.com/aymerick/raymond Index | Examples | Files | Directories

package raymond

import "github.com/aymerick/raymond"

Package raymond provides handlebars evaluation

Code:

source := "<h1>{{title}}</h1><p>{{body.content}}</p>"

ctx := map[string]interface{}{
    "title": "foo",
    "body":  map[string]string{"content": "bar"},
}

// parse template
tpl := MustParse(source)

// evaluate template with context
output := tpl.MustExec(ctx)

// alternatively, for one shots:
// output :=  MustRender(source, ctx)

fmt.Print(output)

Output:

<h1>foo</h1><p>bar</p>

Code:

source := `<div class="post">
  <h1>By {{fullName author}}</h1>
  <div class="body">{{body}}</div>

  <h1>Comments</h1>

  {{#each comments}}
  <h2>By {{fullName author}}</h2>
  <div class="body">{{content}}</div>
  {{/each}}
</div>`

type Person struct {
    FirstName string
    LastName  string
}

type Comment struct {
    Author Person
    Body   string `handlebars:"content"`
}

type Post struct {
    Author   Person
    Body     string
    Comments []Comment
}

ctx := Post{
    Person{"Jean", "Valjean"},
    "Life is difficult",
    []Comment{
        Comment{
            Person{"Marcel", "Beliveau"},
            "LOL!",
        },
    },
}

RegisterHelper("fullName", func(person Person) string {
    return person.FirstName + " " + person.LastName
})

output := MustRender(source, ctx)

fmt.Print(output)

Output:

<div class="post">
  <h1>By Jean Valjean</h1>
  <div class="body">Life is difficult</div>

  <h1>Comments</h1>

  <h2>By Marcel Beliveau</h2>
  <div class="body">LOL!</div>
</div>

Index

Examples

Package Files

data_frame.go escape.go eval.go helper.go partial.go raymond.go string.go template.go utils.go

func Escape Uses

func Escape(s string) string

Escape escapes special HTML characters.

It can be used by helpers that return a SafeString and that need to escape some content by themselves.

Code:

tpl := MustParse("{{link url text}}")

tpl.RegisterHelper("link", func(url string, text string) SafeString {
    return SafeString("<a href='" + Escape(url) + "'>" + Escape(text) + "</a>")
})

ctx := map[string]string{
    "url":  "http://www.aymerick.com/",
    "text": "This is a <em>cool</em> website",
}

result := tpl.MustExec(ctx)
fmt.Print(result)

Output:

<a href='http://www.aymerick.com/'>This is a &lt;em&gt;cool&lt;/em&gt; website</a>

func IsTrue Uses

func IsTrue(obj interface{}) bool

IsTrue returns true if obj is a truthy value.

Code:

output := "Empty array: " + Str(IsTrue([0]string{})) + "\n"
output += "Non empty array: " + Str(IsTrue([1]string{"foo"})) + "\n"

output += "Empty slice: " + Str(IsTrue([]string{})) + "\n"
output += "Non empty slice: " + Str(IsTrue([]string{"foo"})) + "\n"

output += "Empty map: " + Str(IsTrue(map[string]string{})) + "\n"
output += "Non empty map: " + Str(IsTrue(map[string]string{"foo": "bar"})) + "\n"

output += "Empty string: " + Str(IsTrue("")) + "\n"
output += "Non empty string: " + Str(IsTrue("foo")) + "\n"

output += "true bool: " + Str(IsTrue(true)) + "\n"
output += "false bool: " + Str(IsTrue(false)) + "\n"

output += "0 integer: " + Str(IsTrue(0)) + "\n"
output += "positive integer: " + Str(IsTrue(10)) + "\n"
output += "negative integer: " + Str(IsTrue(-10)) + "\n"

output += "0 float: " + Str(IsTrue(0.0)) + "\n"
output += "positive float: " + Str(IsTrue(10.0)) + "\n"
output += "negative integer: " + Str(IsTrue(-10.0)) + "\n"

output += "struct: " + Str(IsTrue(struct{}{})) + "\n"
output += "nil: " + Str(IsTrue(nil)) + "\n"

fmt.Println(output)

Output:

Empty array: false
Non empty array: true
Empty slice: false
Non empty slice: true
Empty map: false
Non empty map: true
Empty string: false
Non empty string: true
true bool: true
false bool: false
0 integer: false
positive integer: true
negative integer: true
0 float: false
positive float: true
negative integer: true
struct: true
nil: false

func MustRender Uses

func MustRender(source string, ctx interface{}) string

MustRender parses a template and evaluates it with given context. It panics on error.

Note that this function call is not optimal as your template is parsed everytime you call it. You should use Parse() function instead.

Code:

tpl := "<h1>{{title}}</h1><p>{{body.content}}</p>"

ctx := map[string]interface{}{
    "title": "foo",
    "body":  map[string]string{"content": "bar"},
}

// render template with context
output := MustRender(tpl, ctx)

fmt.Print(output)

Output:

<h1>foo</h1><p>bar</p>

func RegisterHelper Uses

func RegisterHelper(name string, helper interface{})

RegisterHelper registers a global helper. That helper will be available to all templates.

func RegisterHelpers Uses

func RegisterHelpers(helpers map[string]interface{})

RegisterHelpers registers several global helpers. Those helpers will be available to all templates.

func RegisterPartial Uses

func RegisterPartial(name string, source string)

RegisterPartial registers a global partial. That partial will be available to all templates.

func RegisterPartialTemplate Uses

func RegisterPartialTemplate(name string, tpl *Template)

RegisterPartialTemplate registers a global partial with given parsed template. That partial will be available to all templates.

func RegisterPartials Uses

func RegisterPartials(partials map[string]string)

RegisterPartials registers several global partials. Those partials will be available to all templates.

func RemoveAllHelpers Uses

func RemoveAllHelpers()

RemoveAllHelpers unregisters all global helpers

func RemoveAllPartials Uses

func RemoveAllPartials()

RemoveAllPartials removes all globally registered partials. This does not affect partials registered on a specific template.

func RemoveHelper Uses

func RemoveHelper(name string)

RemoveHelper unregisters a global helper

func RemovePartial Uses

func RemovePartial(name string)

RemovePartial removes the partial registered under the given name. The partial will not be available globally anymore. This does not affect partials registered on a specific template.

func Render Uses

func Render(source string, ctx interface{}) (string, error)

Render parses a template and evaluates it with given context

Note that this function call is not optimal as your template is parsed everytime you call it. You should use Parse() function instead.

Code:

tpl := "<h1>{{title}}</h1><p>{{body.content}}</p>"

ctx := map[string]interface{}{
    "title": "foo",
    "body":  map[string]string{"content": "bar"},
}

// render template with context
output, err := Render(tpl, ctx)
if err != nil {
    panic(err)
}

fmt.Print(output)

Output:

<h1>foo</h1><p>bar</p>

func Str Uses

func Str(value interface{}) string

Str returns string representation of any basic type value.

Code:

output := Str(3) + " foos are " + Str(true) + " and " + Str(-1.25) + " bars are " + Str(false) + "\n"
output += "But you know '" + Str(nil) + "' John Snow\n"
output += "map: " + Str(map[string]string{"foo": "bar"}) + "\n"
output += "array: " + Str([]interface{}{true, 10, "foo", 5, "bar"})

fmt.Println(output)

Output:

3 foos are true and -1.25 bars are false
But you know '' John Snow
map: map[foo:bar]
array: true10foo5bar

type DataFrame Uses

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

DataFrame represents a private data frame.

Cf. private variables documentation at: http://handlebarsjs.com/block_helpers.html

func NewDataFrame Uses

func NewDataFrame() *DataFrame

NewDataFrame instanciates a new private data frame.

func (*DataFrame) Copy Uses

func (p *DataFrame) Copy() *DataFrame

Copy instanciates a new private data frame with receiver as parent.

func (*DataFrame) Get Uses

func (p *DataFrame) Get(key string) interface{}

Get gets a data value.

func (*DataFrame) Set Uses

func (p *DataFrame) Set(key string, val interface{})

Set sets a data value.

type Options Uses

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

Options represents the options argument provided to helpers and context functions.

func (*Options) Ctx Uses

func (options *Options) Ctx() interface{}

Ctx returns current evaluation context.

func (*Options) Data Uses

func (options *Options) Data(name string) interface{}

Data returns private data value.

func (*Options) DataFrame Uses

func (options *Options) DataFrame() *DataFrame

DataFrame returns current private data frame.

func (*Options) DataStr Uses

func (options *Options) DataStr(name string) string

DataStr returns string representation of private data value.

func (*Options) Eval Uses

func (options *Options) Eval(ctx interface{}, field string) interface{}

Eval evaluates field for given context.

func (*Options) Fn Uses

func (options *Options) Fn() string

Fn evaluates block with current evaluation context.

func (*Options) FnCtxData Uses

func (options *Options) FnCtxData(ctx interface{}, data *DataFrame) string

FnCtxData evaluates block with given context and private data frame.

func (*Options) FnData Uses

func (options *Options) FnData(data *DataFrame) string

FnData evaluates block with given private data frame.

func (*Options) FnWith Uses

func (options *Options) FnWith(ctx interface{}) string

FnWith evaluates block with given context.

func (*Options) Hash Uses

func (options *Options) Hash() map[string]interface{}

Hash returns entire hash.

func (*Options) HashProp Uses

func (options *Options) HashProp(name string) interface{}

HashProp returns hash property.

func (*Options) HashStr Uses

func (options *Options) HashStr(name string) string

HashStr returns string representation of hash property.

func (*Options) Inverse Uses

func (options *Options) Inverse() string

Inverse evaluates "else block".

func (*Options) NewDataFrame Uses

func (options *Options) NewDataFrame() *DataFrame

NewDataFrame instanciates a new data frame that is a copy of current evaluation data frame.

Parent of returned data frame is set to current evaluation data frame.

func (*Options) Param Uses

func (options *Options) Param(pos int) interface{}

Param returns parameter at given position.

func (*Options) ParamStr Uses

func (options *Options) ParamStr(pos int) string

ParamStr returns string representation of parameter at given position.

func (*Options) Params Uses

func (options *Options) Params() []interface{}

Params returns all parameters.

func (*Options) Value Uses

func (options *Options) Value(name string) interface{}

Value returns field value from current context.

func (*Options) ValueStr Uses

func (options *Options) ValueStr(name string) string

ValueStr returns string representation of field value from current context.

type SafeString Uses

type SafeString string

SafeString represents a string that must not be escaped.

A SafeString can be returned by helpers to disable escaping.

Code:

RegisterHelper("em", func() SafeString {
    return SafeString("<em>FOO BAR</em>")
})

tpl := MustParse("{{em}}")

result := tpl.MustExec(nil)
fmt.Print(result)

Output:

<em>FOO BAR</em>

type Template Uses

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

Template represents a handlebars template.

func MustParse Uses

func MustParse(source string) *Template

MustParse instanciates a template by parsing given source. It panics on error.

func Parse Uses

func Parse(source string) (*Template, error)

Parse instanciates a template by parsing given source.

func ParseFile Uses

func ParseFile(filePath string) (*Template, error)

ParseFile reads given file and returns parsed template.

func (*Template) Clone Uses

func (tpl *Template) Clone() *Template

Clone returns a copy of that template.

func (*Template) Exec Uses

func (tpl *Template) Exec(ctx interface{}) (result string, err error)

Exec evaluates template with given context.

Code:

source := "<h1>{{title}}</h1><p>{{body.content}}</p>"

ctx := map[string]interface{}{
    "title": "foo",
    "body":  map[string]string{"content": "bar"},
}

// parse template
tpl := MustParse(source)

// evaluate template with context
output, err := tpl.Exec(ctx)
if err != nil {
    panic(err)
}

fmt.Print(output)

Output:

<h1>foo</h1><p>bar</p>

func (*Template) ExecWith Uses

func (tpl *Template) ExecWith(ctx interface{}, privData *DataFrame) (result string, err error)

ExecWith evaluates template with given context and private data frame.

Code:

source := "<h1>{{title}}</h1><p>{{#body}}{{content}} and {{@baz.bat}}{{/body}}</p>"

ctx := map[string]interface{}{
    "title": "foo",
    "body":  map[string]string{"content": "bar"},
}

// parse template
tpl := MustParse(source)

// computes private data frame
frame := NewDataFrame()
frame.Set("baz", map[string]string{"bat": "unicorns"})

// evaluate template
output, err := tpl.ExecWith(ctx, frame)
if err != nil {
    panic(err)
}

fmt.Print(output)

Output:

<h1>foo</h1><p>bar and unicorns</p>

func (*Template) MustExec Uses

func (tpl *Template) MustExec(ctx interface{}) string

MustExec evaluates template with given context. It panics on error.

Code:

source := "<h1>{{title}}</h1><p>{{body.content}}</p>"

ctx := map[string]interface{}{
    "title": "foo",
    "body":  map[string]string{"content": "bar"},
}

// parse template
tpl := MustParse(source)

// evaluate template with context
output := tpl.MustExec(ctx)

fmt.Print(output)

Output:

<h1>foo</h1><p>bar</p>

func (*Template) PrintAST Uses

func (tpl *Template) PrintAST() string

PrintAST returns string representation of parsed template.

Code:

source := "<h1>{{title}}</h1><p>{{#body}}{{content}} and {{@baz.bat}}{{/body}}</p>"

// parse template
tpl := MustParse(source)

// print AST
output := tpl.PrintAST()

fmt.Print(output)

Output:

CONTENT[ '<h1>' ]
{{ PATH:title [] }}
CONTENT[ '</h1><p>' ]
BLOCK:
  PATH:body []
  PROGRAM:
    {{     PATH:content []
 }}
    CONTENT[ ' and ' ]
    {{     @PATH:baz/bat []
 }}
  CONTENT[ '</p>' ]

func (*Template) RegisterHelper Uses

func (tpl *Template) RegisterHelper(name string, helper interface{})

RegisterHelper registers a helper for that template.

func (*Template) RegisterHelpers Uses

func (tpl *Template) RegisterHelpers(helpers map[string]interface{})

RegisterHelpers registers several helpers for that template.

func (*Template) RegisterPartial Uses

func (tpl *Template) RegisterPartial(name string, source string)

RegisterPartial registers a partial for that template.

func (*Template) RegisterPartialFile Uses

func (tpl *Template) RegisterPartialFile(filePath string, name string) error

RegisterPartialFile reads given file and registers its content as a partial with given name.

func (*Template) RegisterPartialFiles Uses

func (tpl *Template) RegisterPartialFiles(filePaths ...string) error

RegisterPartialFiles reads several files and registers them as partials, the filename base is used as the partial name.

func (*Template) RegisterPartialTemplate Uses

func (tpl *Template) RegisterPartialTemplate(name string, template *Template)

RegisterPartialTemplate registers an already parsed partial for that template.

func (*Template) RegisterPartials Uses

func (tpl *Template) RegisterPartials(partials map[string]string)

RegisterPartials registers several partials for that template.

Directories

PathSynopsis
astPackage ast provides structures to represent a handlebars Abstract Syntax Tree, and a Visitor interface to visit that tree.
handlebarsPackage handlebars contains all the tests that come from handlebars.js project.
lexerPackage lexer provides a handlebars tokenizer.
parserPackage parser provides a handlebars syntax analyser.

Package raymond imports 12 packages (graph) and is imported by 80 packages. Updated 2018-03-22. Refresh now. Tools for package owners.